如何从code检索数据注释? (编程) [英] How to retrieve Data Annotations from code? (programmatically)
本文介绍了如何从code检索数据注释? (编程)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我用 System.ComponentModel.DataAnnotations
来为我的实体框架4.1的项目提供验证。
I'm using System.ComponentModel.DataAnnotations
to provide validation for my Entity Framework 4.1 project.
例如:
public class Player
{
[Required]
[MaxLength(30)]
[Display(Name = "Player Name")]
public string PlayerName { get; set; }
[MaxLength(100)]
[Display(Name = "Player Description")]
public string PlayerDescription{ get; set; }
}
我需要检索 Display.Name
注释值的消息显示它如的选择的玩家名是弗兰克。的
I need to retrieve the Display.Name
annotation value to show it in a message such as The chosen "Player Name" is Frank.
=============================================== ==================================
=================================================================================
为什么我会需要检索注释又如:
Another example of why I could need to retrieve annotations:
var playerNameTextBox = new TextBox();
playerNameTextBox.MaxLength = GetAnnotation(myPlayer.PlayerName, MaxLength);
我怎么能这样做?
How can I do that?
推荐答案
扩展方法:
public static T GetAttributeFrom<T>(this object instance, string propertyName) where T : Attribute
{
var attrType = typeof(T);
var property = instance.GetType().GetProperty(propertyName);
return (T)property .GetCustomAttributes(attrType, false).First();
}
code:
var name = player.GetAttributeFrom<DisplayAttribute>("PlayerDescription").Name;
var maxLength = player.GetAttributeFrom<MaxLengthAttribute>("PlayerName").Length;
这篇关于如何从code检索数据注释? (编程)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文