C# 反射教程






4.29/5 (63投票s)
C# 反射教程
引言
反射是指托管代码读取自身元数据的能力,以便在运行时查找程序集、模块和类型信息。换句话说,反射提供了封装程序集、模块和类型的对象。程序通过从其程序集中提取元数据,并使用该元数据来告知用户或修改自身行为来进行自省。反射类似于 C++ RTTI(运行时类型信息),但范围和功能更广。通过在 C# 中使用反射,可以了解对象的详细信息、方法,并在运行时创建对象和调用方法。System.Reflection
命名空间包含类和接口,这些类和接口提供了对已加载类型、方法和字段的托管视图,并具有动态创建和调用类型的能力。在编写使用反射的 C# 代码时,编码人员可以使用 typeof
运算符获取对象的类型,或使用 GetType()
方法获取当前实例的类型。以下是一些演示反射用法的示例代码
示例 1
using System;
using System.Reflection;
public class MyClass
{
public virtual int AddNumb(int numb1,int numb2)
{
int result = numb1 + numb2;
return result;
}
}
class MyMainClass
{
public static int Main()
{
Console.WriteLine ("\nReflection.MethodInfo");
// Create MyClass object
MyClass myClassObj = new MyClass();
// Get the Type information.
Type myTypeObj = myClassObj.GetType();
// Get Method Information.
MethodInfo myMethodInfo = myTypeObj.GetMethod("AddNumb");
object[] mParam = new object[] {5, 10};
// Get and display the Invoke method.
Console.Write("\nFirst method - " + myTypeObj.FullName + " returns " +
myMethodInfo.Invoke(myClassObj, mParam) + "\n");
return 0;
}
}
首先,下面的代码片段将获取 type
信息
Type myTypeObj = Type.GetType("MyClass");
现在,myTypeObj
将拥有关于 MyClass
的所需信息。因此,我们可以使用以下语句之一来检查类是 abstract
类还是常规类
myTypeObj.IsAbstract
或
myTypeObj.IsClass
下面的代码片段将获取方法的信息。在这种情况下,我们感兴趣的方法是 AddNumb
Methodinfo myMethodInfo = myTypeObj.GetMethod("AddNumb");
以下代码片段将调用 AddNumb
方法
myMethodInfo.Invoke(myClassObj, mParam);
//Example2: In this example, we will use the typeof keyword to obtain the
// System.Type object for a type.
Public class MyClass2
{
int answer;
public MyClass2()
{
answer = 0;
}
public int AddNumb(intnumb1, intnumb2)
{
answer = numb1 + numb2;
return answer;
}
}
下面的代码片段获取 MyClass2 类型
的 System.Type
对象。
Type type1 = typeof(MyClass2);
因此,我们将能够通过将 type1
对象传递给 Activator.CreateInstance(type1)
方法来创建 type1
对象的实例。
object obj = Activator.CreateInstance(type1);
然后,我们可以通过首先为将传递给 AddNumb(int, int)
方法的参数创建对象数组来调用 MyClass2
类的 AddNumb
方法。
object[] mParam =newobject[] {5, 10};
最后,我们将通过将方法名 AddNumb
传递给 System.Type.InvokeMember()
以及适当的参数来调用 AddNumb(int, int)
方法。
int res = (int)type1.InvokeMember("AddNumb", BindingFlags.InvokeMethod,null,
obj, mParam);
//Here is the complete code:
using System;
using System.Reflection;
namespace Reflection
{
class Class1
{
public int AddNumb(int numb1, int numb2)
{
int ans = numb1 + numb2;
return ans;
}
[STAThread]
static void Main(string[] args)
{
Type type1 = typeof(Class1);
//Create an instance of the type
object obj = Activator.CreateInstance(type1);
object[] mParam = new object[] {5, 10};
//invoke AddMethod, passing in two parameters
int res = (int)type1.InvokeMember("AddNumb", BindingFlags.InvokeMethod,
null, obj, mParam);
Console.Write("Result: {0} \n", res);
}
}
}