C#中如何使用反射
在C#中,可使用System.Reflection命名空间来使用反射。以下是使用反射的一些经常使用方法:
Type type = typeof(MyClass); // 获得类的类型信息
object obj = Activator.CreateInstance(type); // 创建类的实例
PropertyInfo propertyInfo = type.GetProperty("PropertyName"); // 获得属性信息
MethodInfo methodInfo = type.GetMethod("MethodName"); // 获得方法信息
object result = methodInfo.Invoke(obj, parameters); // 调用方法
propertyInfo.SetValue(obj, value); // 设置属性值
FieldInfo fieldInfo = type.GetField("FieldName"); // 获得字段信息
Attribute attribute = Attribute.GetCustomAttribute(type, typeof(MyAttribute)); // 获得类的特性信息
通过反射,可以在运行时动态获得和操作类型的成员信息,对一些需要在运行时才能肯定的情况下非常有用。但需要注意反射会致使性能开消,应谨慎使用。
TOP