正在阅读:由C++转向C#需要注意的变化(六)由C++转向C#需要注意的变化(六)

2004-11-23 10:08 出处:CSDN 作者:AustinLei 责任编辑:linjixiong


  Console.WriteLine("{0}isa{1}",
  mbrInfo,mbrInfo.MemberType.Format());
  }
  }
  }

  其输出的一部分如下所示:


  System.Type[]GetTypes()isaMethod
  System.Type[]GetExportedTypes()isaMethod
  System.TypeGetType(System.String,Boolean)isaMethod
  System.TypeGetType(System.String)isaMethod
  System.Reflection.AssemblyNameGetName(Boolean)isaMethod
  System.Reflection.AssemblyNameGetName()isaMethod
  Int32GetHashCode()isaMethod
  System.Reflection.AssemblyGetAssembly(System.Type)isaMethod
  System.TypeGetType(System.String,Boolean,Boolean)isaMethod

  动态调用

  一旦发现一个方法,可以使用映射的方法调用它。例如,我们可能需要调用System.Math中的Cos方法(返回一个角的余弦值)。为此,我们需要获得System.Math类的类型信息,如下所示:


  TypetheMathType=Type.GetType("System.Math");

  有了类型信息,我们就可以动态地加载一个类的实例:


  ObjecttheObj=Activator.CreateInstance(theMathType);

  CreateInstance是Activator类的一个静态方法,可以用来对对象进行初始化。

  有了System.Math类的实例后,我们就可以调用Cos方法了。我们还需要准备好一个定义参数类型的数组,因为Cos只需要一个参数(需要求余弦值的角度),因此数组中只需要有一个成员。我们将在数组中赋予一个System.Double类型的Type对象,也就是Cos方法需要的参数的类型:


  Type[]paramTypes=newType[1];
  paramTypes[0]=Type.GetType("System.Double");

  现在我们就可以传递方法的名字了,这个数组定义了Type对象中GetMethod方法的参数的类型:


  MethodInfoCosineInfo=
  theMathType.GetMethod("Cos",paramTypes);

  我们现在得到了MethodInfo类型的对象,我们可以在其上调用相应的方法。为此,我们需要再次在数组中传入参数的实际值:


察看评论详细内容 我要发表评论
作者笔名 简短内容 发表时间
:

键盘也能翻页,试试“← →”键

关注我们

最新资讯离线随时看 聊天吐槽赢奖品