如何从属性中获取值?

如何从属性中获取值?

问题描述:

让我们有一个int放慢参数一个属性在构造函数如何从属性中获取值?

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

    public EntityBindingAttribute(int i) 
    { 
     I = 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

只要属性类具有该属性,它就会工作。 – 2011-03-30 08:33:53

+1

是的,在评论中提到“假设有一个”。将代码更改为使用FirstOrDefault很容易,然后在访问属性之前检查空引用。I.为了清晰起见,在答案中省略了这一点。 – Fung 2011-03-30 10:06:07

您将使用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); 
    } 
} 
+0

哪一种方法是从一个类获得的属性? – user256034 2011-03-30 08:23:40

+0

System.Type实际上是一个System.Reflection.MemberInfo,所以它是相同的方法,就像这个Attribute.GetCustomAttributes(typeof(MyClass)) – 2011-03-30 16:08:28