如何使用反射找到数据注释属性及其参数 [英] How I can find Data Annotation attributes and their parameters using reflection

查看:27
本文介绍了如何使用反射找到数据注释属性及其参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

谢谢

推荐答案

我假设你有这样的事情:

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;

这篇关于如何使用反射找到数据注释属性及其参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆