如何从属性中获取值?

时间:2011-03-30 08:12:55

标签: c# attributes

让我们在ctor中有一个带有int参数的属性

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)]
public class EntityBindingAttribute : Attribute
{
    public int I { get; set; }

    public EntityBindingAttribute(int i)
    {
        I = i;
    }
}

如何使用代码访问此值?

2 个答案:

答案 0 :(得分:3)

您将使用Attribute.GetCustomAttributes Method,其重载与已设置属性的对象匹配。

例如,如果在方法上设置属性,则类似:

MethodInfo mInfo = myClass.GetMethod("MyMethod");
foreach(Attribute attr in Attribute.GetCustomAttributes(mInfo))
{
   if (attr.GetType() == typeof(EntityBindingAttribute))
   {
     int i = ((EntityBindingAttribute)attr).I);
    }
}

答案 1 :(得分:1)

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