Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/94.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 获取属性的参数和值_C#_System.reflection - Fatal编程技术网

C# 获取属性的参数和值

C# 获取属性的参数和值,c#,system.reflection,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 {

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

[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;
       }
}
我设法获得了属性名,但在获取属性构造函数参数的键/值对时遇到了问题

例如,我如何访问属性的构造函数参数和这些值


例如,可以从所需的属性ErrorMessage.Name和ErrorMessage.Value中获取:您需要进一步使用反射,在每个属性上使用
Type.GetProperties
,然后使用
PropertyInfo.GetValue
拉出每个属性公开的属性值

您可以使用
MemberInfo.Name
TypedValue.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;
        }
    }
}

尝试一次查找一种类型的属性:

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

这不是一个好的解决方案。它很难维护,而且很重复。@Jason可能这取决于你的任务是什么。很多时候,您需要检查
RequiredAttribute
是否存在,如果存在,则需要检查其属性设置为什么。如果是那样的话,我会像上面那样做。当然,如果您想找到所有类型的属性,并检查它们碰巧具有哪些属性,那么您将必须使用更多的反射。但是属性的一个典型用法如上所述:只检查一个特定属性,而不关心其他属性(其含义与您无关或未知)。他没有具体说明所需的属性,他显示了两个属性,其中混合了属性。