如何获取DataAnnotation显示名称列表

时间:2018-04-13 09:45:10

标签: c# .net data-annotations

我有一个带有数据注释的类,需要从显示和属性名称中获取字符串列表。

我已经尝试了一些方法。 在方法GetAttributesNames()中。

internal class TVSystemViewData : BaseViewData
        {
            [Display(Name = "BoxType", Description = "")]
            public String BoxType { get; set; }

            [Display(Name = "BoxVendor", Description = "")]
            public String BoxVendor { get; set; }

            [Display(Name = "ClientId", Description = "")]
            public String ClientId { get; set; }

            [Display(Name = "HostName", Description = "")]
            public String HostName { get; set; }

            [Display(Name = "OSVersion", Description = "")]
            public String OSVersion { get; set; }
            [Display(Name = "SerialNumber", Description = "")]
            public String SerialNumber { get; set; }


            internal void GetAttributesNames()
            {
                var listOfFieldNames = typeof(TVSystemViewData)
                .GetProperties()
                .Select(x =>  x.GetCustomAttributes(typeof(DisplayAttribute), true))
                .Where(x => x != null)
                .ToList();

            }
}

2 个答案:

答案 0 :(得分:1)

这可能会有所帮助

internal List<string> GetAttributesNames()  //changed type returned
    {
        return  typeof(TVSystemViewData)
          .GetProperties()                //so far like you did
          .SelectMany(x=>x.GetCustomAttributes(typeof(DisplayAttribute),true) //select many because can have multiple attributes
          .Select(e=>((DisplayAttribute)e))) //change type from generic attribute to DisplayAttribute
          .Where(x => x != null).Select( x => x.Name) //select not null and take only name
          .ToList(); // you know ;)
    }

希望这有帮助

答案 1 :(得分:1)

试试这个:

class Program
{
    static void Main(string[] args)
    {
        var data = new TVSystemViewData();

        var listOfDisplayNames = data.GetAttributesNames();
    }
}

internal class TVSystemViewData
{
    [Display(Name = "XXXXX", Description = "")]
    public String BoxType { get; set; }

    [Display(Name = "BoxVendor", Description = "")]
    public String BoxVendor { get; set; }

    [Display(Name = "ClientId", Description = "")]
    public String ClientId { get; set; }

    [Display(Name = "HostName", Description = "")]
    public String HostName { get; set; }

    [Display(Name = "OSVersion", Description = "")]
    public String OSVersion { get; set; }
    [Display(Name = "SerialNumber", Description = "")]
    public String SerialNumber { get; set; }

    internal List<string> GetAttributesNames()
    {
        return typeof(TVSystemViewData)
            .GetProperties()
            .Select(x => ((DisplayAttribute) x.GetCustomAttribute(typeof(DisplayAttribute), true)).Name)
            .ToList();
    }
}