特性
特性
AttributeUsage特性用法,和查找特性
class Son : Father
{
}
[Help()]
class Father
{
}
//Inherited 是否可以被派生类(子类)和重写成员继承,默认true
//Inherited =false Son(子)类【不可以】继承Father(父)类上的Help特性,
//Inherited =true Son(子)类 【可以】 继承Father(父)类上的Help特性,
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
class HelpAttribute : Attribute
{
}
class Program
{
static void Main(string[] args)
{
//GetCustomAttributes(true) 查找Son继承链上的所有可被继承的特性,
//注: 可被继承的特性是关键!
//[AttributeUsage(AttributeTargets.Class,AllowMultiple =false,Inherited =false)] 【不可以】查找到Father上的特性Help
//[AttributeUsage(AttributeTargets.Class,AllowMultiple =false,Inherited =true )] 【可以】 查找到Father上的特性Help
foreach (var item in typeof(Son).GetCustomAttributes(true))
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
-----------------------------示例2--------------------------------
class FathorAttribute : Attribute
{
public FathorAttribute()
{
Console.WriteLine("FathorAttribute");
}
}
class SonAttribute : FathorAttribute
{
public SonAttribute()
{
Console.WriteLine("SonAttribute");
}
}
[FathorAttribute]
class fa
{
}
class son:fa
{
public static void ss()
{
var res = typeof(son).GetCustomAttributes(typeof(Attribute), true); //为true的时候,可以查找到son的父类fa上的特性。false的时候不能查询到
Console.WriteLine("");
}
}

浙公网安备 33010602011771号