特性 Attribute 的使用
特性 Attribute 是加在类、方法、属性上的标记,通过反射读取。它给代码添加元数据,不改变代码逻辑,但影响框架行为。比如 [Obsolete] 标记废弃方法,[JsonIgnore] 标记不序列化。
自定义特性很简单:继承 Attribute 类。比如定义一个 [Author("作者名")] 特性,通过反射拿到作者信息。序列化框架就是这么工作的。
注意事项:1) 特性只在编译时嵌入元数据;2) 读取特性要用反射;3) 自定义特性类名以 Attribute 结尾,使用时可以省略 Attribute 后缀。
代码示例
// 自定义特性
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorAttribute : Attribute
{
public string Name { get; }
public string Version { get; set; } = "1.0";
public AuthorAttribute(string name) => Name = name;
}
// 使用特性
[Author("Tom", Version = "2.0")]
public class MyService
{
[Author("Jerry")]
public void DoWork() => Console.WriteLine("working");
}
// 通过反射读取特性
Type t = typeof(MyService);
var author = (AuthorAttribute?)Attribute.GetCustomAttribute(t, typeof(AuthorAttribute));
if (author != null)
Console.WriteLine($"作者:{author.Name},版本:{author.Version}");
// 常用内置特性
[Obsolete("请用新方法")]
public void OldMethod() { }
[Serializable]
public class Data { }
学习小结:以上是我学习这个知识点时的笔记和心得。技术学习没有捷径,多写多练多踩坑,自然就掌握了。如果这篇笔记对你有帮助,欢迎继续看看其他文章。