我System.ComponentModel.DataAnnotations用来为我的Entity Framework 4.1项目提供验证。
System.ComponentModel.DataAnnotations
例如:
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注释值以在消息中显示它,例如 “ Player Name”是Frank。
Display.Name
为什么需要检索注释的另一个示例:
var playerNameTextBox = new TextBox(); playerNameTextBox.MaxLength = GetAnnotation(myPlayer.PlayerName, MaxLength);
我怎样才能做到这一点?
扩展方式:
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(); }
码:
var name = player.GetAttributeFrom<DisplayAttribute>(nameof(player.PlayerDescription)).Name; var maxLength = player.GetAttributeFrom<MaxLengthAttribute>(nameof(player.PlayerName)).Length;