开发者

How to get a value from attribute?

开发者 https://www.devze.com 2023-02-20 13:25 出处:网络
Let\'s have a attribute with an int paramter in the ctor [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)]

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消