自定义特性
示例代码:
using System;
namespace Custom
{
class Program
{
static void Main(string[] args)
{
Type type = typeof(Person);
Object[] array = type.GetCustomAttributes(false);
TestAttribute test = array[0] as TestAttribute;
Console.WriteLine(test.Id);
Console.WriteLine(test.Description);
Console.WriteLine(test.Version);
}
}
//1.自定义特性类必需以Attribute结尾
//2.需要继承自Attribute
//3.一般自定义特性类中不定义方法
//4.自定义的特性需要用AttributeUsage指明该特性的适用程序结构
[AttributeUsage(AttributeTargets.Class)] //表示该自定义特性用于Class这种类型
class TestAttribute : Attribute
{
//构造方法
public TestAttribute(int Id, string Description, string Version)
{
this.Id = Id;
this.Description = Description;
this.Version = Version;
}
public int Id;
public string Description;
public string Version;
}
[Test(1, "自定义特性", "1.0.0")