获取属性的参数和值

时间:2013-06-18 14:17:57

标签: c# system.reflection

您好我正在使用反射来迭代此模型属性的属性:

[Required(ErrorMessage = "Username is required")]
[MaxLength(50, ErrorMessage = "Username should not have more then 50 chars")]
[MinLength(25 , ErrorMessage = "Username should have at least 25 chars")]
 public string UserName { get; set; }

 [Required(ErrorMessage = "Password is required")]
 [StringLength(25)]
 public string Password { get; set; }

 public bool RememberMe { get; set; }

foreach (var propertyInfo in type)
       var attr = propertyInfo.CustomAttributes;
       foreach (var customAttributeData in attr)
       {
             var name = customAttributeData.AttributeType.Name;
       }
}

我设法得到了属性名称,但是我在获取属性构造函数参数的键/值对时遇到了麻烦。

我怎样才能访问属性的构造函数参数和值?

一个例子是能够得到:来自Required属性ErrorMessage.Name和ErrorMessage.Value

3 个答案:

答案 0 :(得分:1)

您需要进一步使用反射,在每个属性上使用Type.GetProperties,然后使用PropertyInfo.GetValue来清除每个属性公开公开的属性值。

答案 1 :(得分:1)

您可以使用MemberInfo.NameTypedValue.Value。这是代码:

foreach (var propertyInfo in typeof(YOUR CLASS).GetProperties())
{
    var attr = propertyInfo.GetCustomAttributesData();

    foreach (var customAttributeData in attr)
    {
        foreach (var item in customAttributeData.NamedArguments)
        {
            var name = item.MemberInfo.Name;
            var value = item.TypedValue.Value;
        }
    }
}

答案 2 :(得分:0)

尝试一次查找一种属性:

foreach (var reqAttr in (RequiredAttribute[])propertyInfo.GetCustomAttributes(typeof(RequiredAttribute), false))
{
    // use reqAttr.ErrorMessage and so on, in here
}