一自定义特性
我们主要讲一下如何自定义特性,定义的方式和普通的类定义方式一致,但是,
第一:需要继承标准特性类
第二:需要添加标准特性,用来限制特性的使用范围等
第三:必须要定义构造函数,即使是空的
第四:当有参构造时,必须要有空构造
如下:[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
public class FirstSayAttribute: Attribute{
public FirstSayAttribute() { }
public FirstSayAttribute(string name, int sore,string message) { this.name = name; this.sore = sore; this.message = message; }
public string name { get; set; }
public int sore { get; set; }
public string message { get; set; }
}
二测试类
[FirstSayAttribute(name = "dj", sore = 100, message = "222")]
[FirstSayAttribute(name = "sq", sore = 100, message = "666")]
public class Test
{
}
三执行
class Program
{
static void Main(string[] args)
{
System.Reflection.MemberInfo info = typeof(Test);
FirstSayAttribute[] customAttrLsit = Attribute.GetCustomAttributes(info, typeof(FirstSayAttribute)) as FirstSayAttribute[];
for (int i = 0; i < customAttrLsit.Length; i++)
{
Console.WriteLine("================================================");
Console.WriteLine("创建人:{0}", customAttrLsit[i].name);
Console.WriteLine("创建时间:{0}", customAttrLsit[i].sore);
Console.WriteLine("备注消息:{0}", customAttrLsit[i].message);
}
Console.WriteLine("Hello World!");
Console.ReadKey();
}
}