C# 特性详解
在 C# 中特性Attribute是一种给代码添加额外信息元数据的机制。它不会直接改变代码逻辑而是为类、方法、属性、字段等附加说明供编译器、运行时、框架或程序员读取和使用。简单理解特性 给代码贴标签让程序知道这段代码有什么特殊说明。例如[Obsolete(这个方法已经过时请使用NewMethod)] public void OldMethod() { }这里[Obsolete]就是一个特性它告诉编译器这个方法已经废弃调用时提醒开发者。一、为什么需要特性假设没有特性public class User { public string Name; public int Age; }程序不知道Name 是否必须填写Age 是否需要验证这个类是否需要序列化是否需要映射数据库是否需要参与权限控制如果使用特性public class User { [Required] public string Name { get; set; } [Range(0,120)] public int Age { get; set; } }框架看到Name → 必填 Age → 范围0~120然后自动执行验证。二、特性的基本语法1. 特性写法[特性名称] public class MyClass { }例如[Serializable] public class Person { }2. 多个特性[Serializable] [Obsolete] public class Person { }也可以[Serializable, Obsolete] public class Person { }三、C# 常用内置特性1. Obsolete过时提醒用于标记废弃代码。例如public class Calculator { [Obsolete] public int Add(int a,int b) { return ab; } }调用Calculator cnew Calculator(); c.Add(1,2);提示Add方法已经过时强制报错[Obsolete(请使用AddNew,true)] public int Add(int a,int b) { return ab; }第二个参数false 警告 true 错误2. Serializable序列化表示对象可以转换为二进制数据。[Serializable] public class Student { public string Name; public int Age; }表示Student对象 | ↓ 二进制数据3. Conditional条件编译控制代码是否执行。#define DEBUG class Test { [Conditional(DEBUG)] public void Log() { Console.WriteLine(测试日志); } }如果#define DEBUG存在执行。否则方法调用会被忽略。4. AttributeUsage用于限制自定义特性使用范围。例如[AttributeUsage(AttributeTargets.Class)] public class MyAttribute:Attribute { }表示只能用于[My] class Person { }不能[My] void Test() { }四、自定义特性重点实际开发中大量使用。例如创建一个作者信息特性第一步继承 Attributepublic class AuthorAttribute:Attribute { }规定所有特性必须继承System.Attribute第二步添加属性public class AuthorAttribute:Attribute { public string Name {get;set;} public string Date {get;set;} }第三步使用[Author(Name张三,Date2026)] public class Book { }五、读取特性反射特性本身不会自动执行。需要Reflection反射例如var typetypeof(Book); var attrstype.GetCustomAttributes(); foreach(var attr in attrs) { Console.WriteLine(attr); }输出AuthorAttribute读取具体信息AuthorAttribute author (AuthorAttribute)Attribute.GetCustomAttribute( typeof(Book), typeof(AuthorAttribute) ); Console.WriteLine(author.Name);结果张三六、特性参数类型特性只能接受允许✅ 基本类型int string bool double✅ 枚举enum Level { Low, High }使用[My(Level.High)]✅ Type类型[Service(typeof(User))]不能❌ 对象new User()❌ ListListstring七、特性的实际应用1. ASP.NET Core 路由例如[HttpGet] public IActionResult GetUser() { }作用告诉框架这个方法处理GET请求2. 数据验证public class User { [Required] public string Name {get;set;} [EmailAddress] public string Email {get;set;} }框架自动验证。3. ORM数据库映射例如public class User { [Key] public int Id {get;set;} [Column(user_name)] public string Name {get;set;} }告诉 ORMId 是主键 Name对应数据库字段 user_name4. JSON序列化public class User { [JsonIgnore] public string Password {get;set;} }结果{ Name:Tom }Password不会输出。八、特性执行流程完整过程源代码 ↓ [Attribute] ↓ 编译器保存元数据 ↓ 程序集 DLL ↓ 反射读取 ↓ 框架执行对应功能九、特性 vs 接口很多初学者容易混淆。接口表示你必须拥有某种能力例如interface IFly { void Fly(); }飞机class Plane:IFly { }特性表示给你添加说明例如[Flying] class Plane { }区别接口特性作用约束行为添加信息是否必须实现方法是否运行时读取少经常典型用途多态框架配置十、企业开发常见特性体系学习 C# 后期必须掌握基础Attribute AttributeUsage ReflectionWeb开发[ApiController] [Route] [HttpGet] [Authorize]数据库[Key] [Table] [Column] [ForeignKey]序列化[JsonProperty] [JsonIgnore] [Serializable]AOP编程例如[Log] [Transaction] [Cache]自动实现调用前记录日志 执行事务 缓存结果