一、特性的作用
将额外的数据关联到属性或者其它构造的一种方式
二、如何自定义特性
class TestAttribute:System.Attribute
{
public TestAttribute (string name)
{
this.Name = name;
}
public string Name { get; set; }
public static void GetValue()
{
}
}
class Test2Attribute : System.Attribute
{
public Test2Attribute (string name)
{
this.Name = name;
}
public string Name { get; set; }
public static void GetValue()
{
}
}
三、如何将特性关联到特性构造
[Test("小王") ]//利用构造器来初始化特性
[Test2("小宋")]
public class Father
{
}
public class Me:Father
{
}
[Test2("小陈")]
public class Son:Me
{
}
注意上述关联特性时,省略了定义特性时的Attribute后缀
四、和特性的相关数据
1)IsDefined判断特性是否应用到了某个构造上
Me sld = new Me();
Type t = sld.GetType();
bool def = t.IsDefined(typeof(TestAttribute ), true);//第二个参数为true代表查找该类的父类以及往上的继承链中是否应用了指定的特性
if (def)
Console.WriteLine("MyAttribute is defined!");
2)GetCustomAttributes 获取构造上应用的特性集合
var array = t.GetCustomAttributes(true );
foreach (var item in array)
{
TestAttribute testAttribute = item as TestAttribute;
Test2Attribute test2Attribute = item as Test2Attribute;//将特性转换为自定义的特性类型的对象,从而获取数据
if(testAttribute !=null)
{
Console.WriteLine(testAttribute .Name );
}
if(test2Attribute !=null )
{
Console.WriteLine(test2Attribute.Name );
}
}
3)限制特性能够修饰的构造
AttributeUsage用于限制特性修饰特性的构造,比如属性
[AttributeUsage(AttributeTargets.Property)]//将Test2特性限定为修饰属性
class Test2Attribute : System.Attribute
{
public Test2Attribute(string name)
{
this.Name = name;
}
public string Name { get; set; }
public double Height { get; set; }
public static void GetValue()
{
}
}
调用
[Test2("小陈", Height = 180)]//用于修饰类时报错
public class Son : Me
{
[Test2("小陈", Height = 180)]//用于修饰属性时Ok
public int Age { get; set; }
}
4)使用命名参数访问特性的成员
Test2特性中有一个Height属性
class Test2Attribute : System.Attribute
{
public Test2Attribute(string name)
{
this.Name = name;
}
public string Name { get; set; }
public double Height { get; set; }
public static void GetValue()
{
}
}
调用
public class Son : Me
{
[Test2("小陈", Height = 180)]//可以直接在使用特性时,对Height赋初始值
public int Age { get; set; }
}
5)预定义特性
[Conditional("ConditionA")]
private void TestPreSelfDefineAttribute()
{
Console.WriteLine("我是预定义特性");
}
调用
TestPreSelfDefineAttribute();//此代码不执行,因为没有定义
#define ConditionA
添加预定义后,再执行代码就Ok
67)标定过时的代码
Obsolete特性将代码标记为过时的代码
[Obsolete("过时的代码")]
private void ObsoleteMethod()//如果在程序中调用,则会提示警告,而特性中传入的字符串就是警告的信息
{
Console.WriteLine("我是过时的代码");
}