通过反射可动态获取类型信息、创建对象并调用成员。使用 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]]");
<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 等核心操作,就能实现大多数动态需求。
以上就是C#的反射(Reflection)是什么?如何动态获取类型信息并调用方法?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号