通过反射可动态获取类型信息、创建对象并调用成员。使用 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 }); // 返回 8Console.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 等核心操作,就能实现大多数动态需求。
以上就是C#的反射(Reflection)是什么?如何动态获取类型信息并调用方法?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1442028.html
微信扫一扫
支付宝扫一扫