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

本文关键字:属性 参数 注释 数据 何使用 反射 | 更新日期: 2023-09-27 18:12:12

我有一些数据注释属性,像这样:

[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;