一尘不染

如何从代码中检索数据注释?(以编程方式)

c#

System.ComponentModel.DataAnnotations用来为我的Entity Framework 4.1项目提供验证。

例如:

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。

==================================================

为什么需要检索注释的另一个示例:

var playerNameTextBox = new TextBox();
playerNameTextBox.MaxLength = GetAnnotation(myPlayer.PlayerName, MaxLength);

我怎样才能做到这一点?


阅读 234

收藏
2020-05-19

共1个答案

一尘不染

扩展方式:

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;
2020-05-19