C# 如何使用反射查找数据注释属性及其参数

C# 如何使用反射查找数据注释属性及其参数,c#,reflection,c#-4.0,attributes,data-annotations,C#,Reflection,C# 4.0,Attributes,Data Annotations,我有一些数据注释属性,如下所示: [StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")] [StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")] public string FirstName {g

我有一些数据注释属性,如下所示:

[StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")]
[StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")]
public string FirstName {get;set;}
如何使用反射查找数据注释属性及其参数


谢谢

我想你有这样的东西:

[StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")]
[StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")]
public string FirstName {get;set;}
要从中获取属性和属性,请执行以下操作:

StringLengthAttribute strLenAttr = 
  typeof(Person).GetProperty("FirstName").GetCustomAttributes(
  typeof(StringLengthAttribute), false).Cast<StringLengthAttribute>().Single();


int maxLen = strLenAttribute.MaximumLength;
StringLengthAttribute strLenAttr=
typeof(Person).GetProperty(“FirstName”).GetCustomAttributes(
typeof(StringLengthAttribute),false.Cast().Single();
int maxLen=strLenAttribute.MaximumLength;