背景:公共语言运行时允许程序添加类似关键字描述的声明,叫做Attribute,它对程序中的元素进行标注,如类型,字段,方法和属性等
定义自定义特性
//继承Attribute,即可实现自定义特性public class DebugAttribute:Attribute{//debug编号public string DebugNo{get;set;}//开发人员姓名public string Name{get;set;}//开发日期public string Date{get;set;}//作用描述public string Description{get;set;}public DebugAttribute()){}public DebugAttribute(string debugNo,string name,string date,string description){this.DebugNo = debugNo;this.Name = name;this.Date=date;this.Description = description;}}
使用自定义特性
public class Unit{[Debug(DebugNo="001",Name="Rotu",Date="2019/10/10",Description="测试输出")]public void ShowMessage(){Console.Write("测试输出");}}static void Main(string[] args){Unit unit = new Unit();foreach(var item in unit.GetType().GetMethods()){DebugAttribute debug = Attribute.GetCustomAttribute(item,typeof(DebugAttribute)) asDebugAttribute;if(debug! = null){Console.Write(debug.DebugNo);}}}
