背景:公共语言运行时允许程序添加类似关键字描述的声明,叫做Attribute,它对程序中的元素进行标注,如类型,字段,方法和属性等

    定义自定义特性

    1. //继承Attribute,即可实现自定义特性
    2. public class DebugAttribute:Attribute
    3. {
    4. //debug编号
    5. public string DebugNo{get;set;}
    6. //开发人员姓名
    7. public string Name{get;set;}
    8. //开发日期
    9. public string Date{get;set;}
    10. //作用描述
    11. public string Description{get;set;}
    12. public DebugAttribute())
    13. {
    14. }
    15. public DebugAttribute(string debugNo,string name,string date,string description)
    16. {
    17. this.DebugNo = debugNo;
    18. this.Name = name;
    19. this.Date=date;
    20. this.Description = description;
    21. }
    22. }

    使用自定义特性

    1. public class Unit
    2. {
    3. [Debug(DebugNo="001",Name="Rotu",Date="2019/10/10",Description="测试输出")]
    4. public void ShowMessage()
    5. {
    6. Console.Write("测试输出");
    7. }
    8. }
    9. static void Main(string[] args)
    10. {
    11. Unit unit = new Unit();
    12. foreach(var item in unit.GetType().GetMethods())
    13. {
    14. DebugAttribute debug = Attribute.GetCustomAttribute(item,typeof(DebugAttribute)) as
    15. DebugAttribute;
    16. if(debug! = null)
    17. {
    18. Console.Write(debug.DebugNo);
    19. }
    20. }
    21. }