通过反射可动态获取类型信息、创建对象并调用成员。使用 typeof 或 GetType() 获取 Type 对象,查询名称、命名空间等元数据;通过 Activator.CreateInstance 创建实例,支持无参或有参构造函数;利用 GetMethod 获取 MethodInfo 后调用方法,配合 BindingFlags 可访问私有成员;PropertyInfo 和 FieldInfo 分别用于读写属性与字段值;反射性能较低,建议缓存 Type 和 MethodInfo 或结合委托优化。

反射(Reflection) 是 C# 提供的一种强大机制,允许程序在运行时动态获取类型信息、创建对象、调用方法、访问字段和属性等,而不需要在编译时知道这些类型的细节。它通过 System.Reflection 命名空间实现,适用于插件架构、序列化、ORM 框架、依赖注入等场景。
如何使用反射获取类型信息?
你可以通过 typeof、GetType() 或 Type.GetType(string) 获取 Type 对象,进而查询类的结构。
例如:
// 获取类型
Type type = typeof(string);
// 或从实例获取
object obj = "hello";
Type type2 = obj.GetType();
// 或通过字符串名称获取(需完整命名空间)
Type type3 = Type.GetType("System.Collections.Generic.List`1[[System.Int32]]");
// 查看类型信息
Console.WriteLine(type.Name); // 输出类型名
Console.WriteLine(type.Namespace); // 命名空间
Console.WriteLine(type.IsClass); // 是否是类
如何动态创建对象?
使用 Activator.CreateInstance 可以根据 Type 创建实例。
Type type = typeof(List); var list = Activator.CreateInstance(type);
如果构造函数有参数,也可以传入:
Type type = typeof(Student); var student = Activator.CreateInstance(type, "张三", 20);
如何动态调用方法?
通过 GetMethod 获取 MethodInfo 对象,再用 Invoke 调用方法。
public class Calculator
{
public int Add(int a, int b) => a + b;
}
// 反射调用 Add 方法
Type calcType = typeof(Calculator);
var calc = Activator.CreateInstance(calcType);
MethodInfo method = calcType.GetMethod("Add");
var result = method.Invoke(calc, new object[] { 5, 3 }); // 返回 8
Console.WriteLine(result);
支持调用私有方法,只需指定 BindingFlags:
MethodInfo privateMethod = type.GetMethod("PrivateMethod",
BindingFlags.NonPublic | BindingFlags.Instance);
访问属性和字段
可以读写属性或字段值:
PropertyInfo prop = type.GetProperty("Name");
prop.SetValue(obj, "李四");
string name = (string)prop.GetValue(obj);
FieldInfo field = type.GetField("age", BindingFlags.NonPublic | BindingFlags.Instance);
field.SetValue(obj, 25);
反射虽然灵活,但性能低于直接调用,建议缓存 Type 和 MethodInfo 对象,或结合委托(如 Expression Tree 或 Delegate.CreateDelegate)提升效率。
基本上就这些,掌握 Type、Activator、GetMethod、Invoke 等核心操作,就能实现大多数动态需求。










