第9章 - 特性
嗨,朋友!我是长安。
特性(Attribute)为代码元素添加元数据信息。
🏷️ 使用特性
[Obsolete("此方法已过时,请使用NewMethod")]
void OldMethod()
{
// ...
}
[Serializable]
class Person
{
public string Name { get; set; }
}
🎯 自定义特性
[AttributeUsage(AttributeTargets.Class)]
class AuthorAttribute : Attribute
{
public string Name { get; set; }
public AuthorAttribute(string name)
{
Name = name;
}
}
[Author("长安")]
class MyClass
{
}
📝 本章小结
- 特性为代码添加元数据
- 常用特性:Obsolete、Serializable等
- 可以自定义特性
- 配合反射使用
