C#的反射(Reflection)是什么?如何动态获取类型信息并调用方法?

来源:这里教程网 时间:2026-02-21 17:31:08 作者:

反射(Reflection) 是 C# 提供的一种强大机制,允许程序在运行时动态获取类型信息、创建对象、调用方法、访问字段和属性等,而不需要在编译时知道这些类型的细节。它通过 System.Reflection 命名空间实现,适用于插件架构、序列化、ORM 框架、依赖注入等场景。

如何使用反射获取类型信息?

你可以通过 typeofGetType()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]]");
<p>// 查看类型信息
Console.WriteLine(type.Name);        // 输出类型名
Console.WriteLine(type.Namespace);   // 命名空间
Console.WriteLine(type.IsClass);     // 是否是类</p>

如何动态创建对象?

使用 Activator.CreateInstance 可以根据 Type 创建实例。

Type type = typeof(List<int>);
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;
}
<p>// 反射调用 Add 方法
Type calcType = typeof(Calculator);
var calc = Activator.CreateInstance(calcType);</p><p>MethodInfo method = calcType.GetMethod("Add");
var result = method.Invoke(calc, new object[] { 5, 3 }); // 返回 8
Console.WriteLine(result);</p>

支持调用私有方法,只需指定 BindingFlags:

MethodInfo privateMethod = type.GetMethod("PrivateMethod", 
    BindingFlags.NonPublic | BindingFlags.Instance);

访问属性和字段

可以读写属性或字段值:

PropertyInfo prop = type.GetProperty("Name");
prop.SetValue(obj, "李四");
string name = (string)prop.GetValue(obj);
<p>FieldInfo field = type.GetField("age", BindingFlags.NonPublic | BindingFlags.Instance);
field.SetValue(obj, 25);</p>

反射虽然灵活,但性能低于直接调用,建议缓存 Type 和 MethodInfo 对象,或结合委托(如 Expression Tree 或 Delegate.CreateDelegate)提升效率。

基本上就这些,掌握 Type、Activator、GetMethod、Invoke 等核心操作,就能实现大多数动态需求。

相关推荐

热文推荐