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

天涯浪子 提交于 2019-11-29 15:29:59

Attributes are always used with reflection. They are baked into the metadata of the types during compile time and the only way to read them is through reflection. Attributes are used when you want write a type and you want to associate some metadata with it which could be used by consumers of this type.

The simplest and most elegant way to use an attribute from another block of code is to use a property instead of an attribute.

See http://blogs.msdn.com/b/ericlippert/archive/2009/02/02/properties-vs-attributes.aspx for a discussion of the differences between properties and attributes.

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!