[AttributeUsage(AttributeTargets.Field|AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class MyAttribute:Attribute
{
public int Index;
public MyAttribute(int index)
{
Index = index;
}
}
[My(250)]//特性允许类和属性的使用
class Class1
{
[My(0)][My(1)]//AllowMultiple允许多个
public int A;
[My(2)]
public bool B;
}
class Class2 : Class1
{
//Inherited允许类继承特性内容,false时不会有Class1的特性
}
static void Main(string[] args)
{
//通过反射获取特性的类容,根据实际需要做不同处理
Type t = typeof(Class1);
MyAttribute attribute = t.GetCustomAttribute(typeof(MyAttribute)) as MyAttribute;
Console.WriteLine("Class1的特性Index:" + attribute.Index);
FieldInfo[] fieldInfos = t.GetFields();
foreach (var i in fieldInfos)
{
object[] mys = i.GetCustomAttributes(false);
foreach (var j in mys)
{
MyAttribute my = j as MyAttribute;
Console.WriteLine(i.Name + "的特性Index:" + my.Index);
}
}
Console.WriteLine();Console.WriteLine("继承的类也有特性");
t = typeof(Class2);
attribute = t.GetCustomAttribute(typeof(MyAttribute)) as MyAttribute;
Console.WriteLine("Class2的特性Index:" + attribute.Index);
fieldInfos = t.GetFields();
foreach (var i in fieldInfos)
{
object[] mys = i.GetCustomAttributes(false);
foreach (var j in mys)
{
MyAttribute my = j as MyAttribute;
Console.WriteLine(i.Name + "的特性Index:" + my.Index);
}
}
Console.ReadKey();
}都挺简单的,解析看注释,输出:
