特性
特性就是一个类,是直接/间接继承了Attribute
约定俗成是以Attribute结尾,在标记的时候以[]包裹 ,尾部的Attribute可以省略
通过反编译之后,在中间语言IL中我们发现标记特性的源苏内部都生成了一个Custom
1 ///2 /// 自定义特性 3 /// AllowMultiple= true ;标记在特性上的特性,其实是对于特性的一种约束 4 /// Inherited =true 约束当前特性是否可以继承 5 /// AttributeTargets.All 当前特性可以标记在所有的元素上 6 /// AttributeUsge在定义特性的时候,对特性的一种约束, 在声明特性的时候 ,加上这个相当于明确这个特性可以标记在那些地方 7 /// 8 [AttributeUsage(AttributeTargets.All,AllowMultiple =true,Inherited =true)] 9 public class CustomAttribute : Attribute 10 { 11 public CustomAttribute() { }//无参构造函数 12 public CustomAttribute(string s ) { }//有参构造函数 13 public int id { get; set; } //属性 14 public string name { get; set; } 15 16 public string age;//字段 17 public void who() { }//函数 18 } 19 20 public class student 21 { 22 [Custom("123",id=1,name="hjh")]//标记特性就是实例化 23 [Custom]//标记特性就是实例化 24 public int MyProperty { get; set; } 25 26 }
可以配合反射使用