What's the simplest most elegant way to utilize a custom attribute

后端 未结 3 1637
天涯浪人
天涯浪人 2020-12-20 23:50

So a little confession, I\'ve never written an attribute class. I understand they serve the purpose of decorating classes with flags or extra functionality possibly.

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-21 00:36

    First create your attribute

    public class ImportableAttribute : Attribute
    {
    
    }
    

    Then a class with a item that uses the Attribute

    [ImportableAttribute]
    public class ImportClass
    {
        [ImportableAttribute]
        public string Item {get; set;}
    }
    

    Then check if that property uses that attribute. Can be done with classes to.. Of course :)

    PropertyInfo property = typeof(ImportClass).GetProperty("Item");
    
    if (property.IsDefined(typeof(ImportableAttribute),true))
    {
         // do something
    }
    

    With a class:

    typeof(ImportClass).IsDefined(typeof(ImportableAttribute), true);
    

提交回复
热议问题