C#的元数据和反射
反射和new是一个相对的概念
new 是在编译的时候创建一个类的实例对象,这个要提前知道
反射不需要提前知道,反射更适合用在通用模块上
反射:获得类的一些元数据信息
new 是在编译的时候创建一个类的实例对象,这个要提前知道
反射不需要提前知道,反射更适合用在通用模块上
反射:获得类的一些元数据信息
using System; using System.Reflection; class Program { static void Main() { Type type = typeof(Person); // 获取类型 Console.WriteLine("类名: " + type.Name); Console.WriteLine("命名空间: " + type.Namespace); Console.WriteLine("属性列表:"); foreach (PropertyInfo prop in type.GetProperties()) { Console.WriteLine(prop.Name + " - " + prop.PropertyType); } } } public class Person { public string Name { get; set; } public int Age { get; set; } }
//输出
类名: Person
命名空间:
属性列表:
Name - System.String
Age - System.Int32
//调用实例方法
using System; using System.Reflection; class Person { public void SayHello(string name) { Console.WriteLine($"Hello, {name}!"); } } class Program { static void Main() { // 1. 获取类型 Type type = typeof(Person); // 2. 创建实例 object instance = Activator.CreateInstance(type); // 3. 获取方法信息 MethodInfo method = type.GetMethod("SayHello"); // 4. 调用方法 method.Invoke(instance, new object[] { "Tom" }); } }
class Utility { public static void PrintMessage(string message) { Console.WriteLine("Message: " + message); } } class Program { static void Main() { Type type = typeof(Utility); MethodInfo method = type.GetMethod("PrintMessage"); // 调用静态方法,不需要实例 method.Invoke(null, new object[] { "Hello, World!" }); } }
特性 定义特性 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class MyCustomAttribute : Attribute { public string Description { get; } public MyCustomAttribute(string description) { Description = description; } } 使用特性 [MyCustomAttribute("这是一个测试类")] public class TestClass { [MyCustomAttribute("这是一个测试方法")] public void TestMethod() { } } 读取特性 Type type = typeof(TestClass); object[] attributes = type.GetCustomAttributes(typeof(MyCustomAttribute), false); foreach (MyCustomAttribute attr in attributes) { Console.WriteLine("特性描述: " + attr.Description); } 特性和反射结合 MethodInfo method = typeof(TestClass).GetMethod("TestMethod"); var attributes = method.GetCustomAttributes(typeof(MyCustomAttribute), false); foreach (MyCustomAttribute attr in attributes) { Console.WriteLine("方法上的特性描述: " + attr.Description); }
静,静,静
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!