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); }
静,静,静

浙公网安备 33010602011771号