反射是编程的读取与类型相关联的元数据的行为,通过元数据,你能了解它是什么类型以及它是由什么构成的(方法、属性、基类)。
反射服务在system.Reflection命名空间中定义,它在和属性一起使用时最有用。属性是一种向类型添加信息并影响类型行为的方法。
反射还允许在运行期间定义新类型,并生成相应的IL代码和元数据(使用在System.Reflection.Emit命名空间中的各种服务。
System.Type
基类Object定义了GetType()方法,使得你能对任何.NET对象调用这个方法
public class MyClass
{ ... }
int number = 0;
MyClass obj = new MyClass();
Type type1 = number.GetType();
Type type2 = number.GetType();
typeof运算符允许你直接检索与一个类型相关联的Type值,而无需实例化该类型的一个对象
Type type1 = typeof(int);
Type type2 = typeof(MyClass);
Type使你可以获取类型的元数据
Type type = typeof(MyClass);
string name = type.ToString();
Debug.Assert(name == “MyClass”);
示例:使用Type.GetMethods()来反射一个类型的公共方法
using System.Reflection;
public class MyClass
{
public MyClass()
{}
public void Method1()
{}
public static void Method2()
{}
protected void Method3()
{}
protected void Method4()
{}
}
//客户端代码
Type type = typeof(MyClass);
MethodInfo[] methodInfoArray = type.GetMethods();
//跟踪所有的公共方法
foreach (MethodInfo methodInfo in methodInfoArray)
{
Trace.WriteLine(methodInfo.Name);
}
//输出
GetHashCode
Equals
ToString
Method1
Method2
GetType
GetMethods()的另一个版本,接受一个参数,告知如何绑定到该类型:
public abstract MethodInfo[] GetMethods(BindingFlags bindingAttr);
BindingFlags枚举,指定:实例方法、静态方法、非公共方法等
取得方法的MethodInfo对象,就可以调用它,即使该方法是受保护的或是私有的:
public object Invoke(object obj, object[] parameters);
晚绑定调用
示例:使用反射调用对象的私有方法
using System.Reflection;
public class MyClass
{
public MyClass()
{ ... }
public void Method1()
{ ... }
public void Method2()
{ ... }
public static void Method5()
{ ... }
protected void Method3()
{ ... }
private void Method4()
{ ... }
}
//客户端代码
MyClass obj =- new MyClass();
Type type = typeof(MyClass);
MethodInfo[] methodInfoArray;
methodInfoArray = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
//仅调用私有方法
foreach (MethodInfo methodInfo in methodInfoArray)
{
if (methodInfo.IsPrivate)
{
methodInfo.Invoke(obj, null);
}
}
GetMethod() ----------- MethodInfo
GetConstructors()、 GetConstructor() ------------------ ConstructorInfo
GetMember()、GetMembers()
GetEvent()、GetEvents()
本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/tongdoudpj/archive/2007/08/28/1762703.aspx