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

Ari*_*ian 8 c# reflection attributes data-annotations c#-4.0

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

[StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")]
Run Code Online (Sandbox Code Playgroud)

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

谢谢

And*_*bel 13

我假设你有这样的事情:

[StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")]
public string FirstName {get;set;}
Run Code Online (Sandbox Code Playgroud)

要从中获取属性和属性:

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


int maxLen = strLenAttribute.MaximumLength;
Run Code Online (Sandbox Code Playgroud)