前置知识: C#

反射与特性应用

1 minAdvanced2026/6/14

C#反射与特性(Attribute)应用详解。

1. 反射

var type = typeof(User);
var props = type.GetProperties();
var methods = type.GetMethods();

// 创建实例
var instance = Activator.CreateInstance(type);

// 调用方法
var method = type.GetMethod("GetName");
var result = method.Invoke(instance, null);

2. 特性定义与使用

[AttributeUsage(AttributeTargets.Property)]
class ColumnAttribute : Attribute {
    public string Name { get; }
    public ColumnAttribute(string name) => Name = name;
}

class User {
    [Column("user_name")]
    public string Name { get; set; }
}

3. 运行时读取特性

var prop = typeof(User).GetProperty("Name");
var attr = prop.GetCustomAttribute<ColumnAttribute>();
Console.WriteLine(attr.Name);  // "user_name"

4. 实际应用

  • ORM 映射(Entity Framework)
  • 序列化控制(JsonSerializer)
  • 依赖注入标记
  • 单元测试框架([Test], [SetUp])