How I can find Data Annotation attributes and their parameters using reflection

醉酒当歌 提交于 2019-11-27 06:03:33

问题


I have some data annotation attribute like this:

[StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")]

How I can Find Data Annotation attributes and their parameters using reflection?

thanks


回答1:


I assume you have something like this:

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

To get the attribute and a property from it:

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


int maxLen = strLenAttribute.MaximumLength;


来源:https://stackoverflow.com/questions/7864662/how-i-can-find-data-annotation-attributes-and-their-parameters-using-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!