浅谈反射

本文详细介绍了C#中的反射机制,包括如何使用反射获取类型信息、调用私有方法等内容。反射是.NET平台的一项强大特性,能够让程序在运行时动态地获取类型信息并操作对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

反射是编程的读取与类型相关联的元数据的行为,通过元数据,你能了解它是什么类型以及它是由什么构成的(方法、属性、基类)。

  反射服务在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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值