特性的用处
特性可以向程序中添加元数据(数据的数据:对数据进行解析的数据)
特性的使用
特性可以通过反射技术 进行获取 处理
特性的创建
自定义特性 需要继承Attribute类 类名后缀可带Attribute 不带也可以
public class AuthorAttribute:Attribute
{
private string name;
public double version;
public AuthorAttribute(string name, double version =1.0)
{
this.name = name;
this.version = version;
}
}
AttributeUsage
控制自定义特性的使用,有两个构造函数
AttributeUsageAttribute(AttributeTargets validOn)
//AllowMultiple 是否可以多次使用
//inherited 继承类是否可以继承此特性
AttributeUsageAttribute(AttributeTargets validOn, bool allowMultiple, inherited)
//AttributeTargets 枚举
public enum AttributeTargets
{
Assembly = 0x1,
Module = 0x2,
Class = 0x4,
Struct = 0x8,
Enum = 0x10,
Constructor = 0x20,
Method = 0x40,
Property = 0x80,
Field = 0x100,
Event = 0x200,
Interface = 0x400,
Parameter = 0x800,
Delegate = 0x1000,
ReturnValue = 0x2000,
GenericParameter = 0x4000,
All = 0x7FFF
}
反射中的使用
[Author("P. Ackerman", version = 1.1)]
class SampleClass
//在概念上等效于:
Author anonymousAuthorObject = new Author("P. Ackerman");
anonymousAuthorObject.version = 1.1;
当 查询 SampleClass 来获取特性后才会执行以上代码
SampleClass 调用 GetCustomAttributes 会导致按上述方式构造并初始化一个 Author 对象。如果该类具有其他特性,则按相似的方式构造其他特性对象。
GetCustomAttributes 返回 Author 对象和数组中的任何其他特性对象。之后就可以对此数组进行迭代,确定根据每个数组元素的类型所应用的特性,并从特性对象中提取信息。
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct,AllowMultiple =true,Inherited =false)]
public class Author:Attribute
{
private string name;
public double version;
public Author(string name, double version =1.0)
{
this.name = name;
this.version = version;
}
public string GetName()
{
return this.name;
}
}
class Program
{
static void Main(string[] args)
{
PrintAuthorInfo(typeof(IndiaBook));
Console.ReadKey();
}
private static void PrintAuthorInfo(Type t)
{
Attribute[] attrs = Attribute.GetCustomAttributes(t);
foreach(var attr in attrs)
{
if(attr is Author)
{
Author a = (Author)attr;
Console.WriteLine("{0},version{1}",a.GetName(),a.version);
}
}
}
}
[Author("EnglishBook001", 1.0)]
public class EnglishBook
{
}
[Author("ChineseBook001",2.0)]
public class ChineseBook
{
}
[Author("india",1.0),Author("india002",2.0)]
public class IndiaBook: ChineseBook
{
}