How to get a value from attribute?
Let's have a attribute with an int paramter in the ctor
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)]
public class EntityBindingA开发者_如何转开发ttribute : Attribute
{
public int I { get; set; }
public EntityBindingAttribute(int i)
{
I = i;
}
}
How can I access this value using code ?
You would use the Attribute.GetCustomAttributes Method, with the overload that matches the object where the attribute has been set.
For example if the attribute is set on a method, something like:
MethodInfo mInfo = myClass.GetMethod("MyMethod");
foreach(Attribute attr in Attribute.GetCustomAttributes(mInfo))
{
if (attr.GetType() == typeof(EntityBindingAttribute))
{
int i = ((EntityBindingAttribute)attr).I);
}
}
// Get all the attributes for the class
Attribute[] _attributes = Attribute.GetCustomAttributes(typeof(NameOfYourClass));
// Get a value from the first attribute of the given type assuming there is one
int _i = _attributes.Where(_a => _a is EntityBindingAttribute).First().I;
精彩评论