【问题标题】:Define custom titles on properties of objects在对象的属性上定义自定义标题
【发布时间】:2016-09-02 09:13:05
【问题描述】:

我有一个定义为

的类的对象列表
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
} 

var personList = new List<Person>();
personList.Add(new Person
   {
        FirstName = "Alex",
        LastName = "Friedman",
        Age = 27
   });

并将该列表输出为表格,其中属性名称作为列标题 (full source code)

var propertyArray = typeof(T).GetProperties();
foreach (var prop in propertyArray)
     result.AppendFormat("<th>{0}</th>", prop.Name);  

得到

FirstName  | LastName  | Age
----------------------------------
Alex         Friedman    27

我想要一些自定义标题,例如

First Name | Last Name | Age 

问题:如何为 Person 类的每个属性定义列标题?我应该在属性上使用自定义属性还是有更好的方法?

【问题讨论】:

  • 可以使用DisplayName-Attribute,通过反射获取值
  • 我会按照你的建议使用属性
  • @MANISH KUMAR CHOUDHARY:什么?只是为了提属性?

标签: c#


【解决方案1】:

这是我在你的情况下会做的一种方法。这很简单,而且很容易解释:

 var propertyArray = typeof(T).GetProperties();
      foreach (var prop in propertyArray) { 
        foreach (var customAttr in prop.GetCustomAttributes(true)) {
          if (customAttr is DisplayNameAttribute) {//<--- DisplayName
            if (String.IsNullOrEmpty(headerStyle)) {
              result.AppendFormat("<th>{0}</th>", (customAttr as DisplayNameAttribute).DisplayName);
            } else {
              result.AppendFormat("<th class=\"{0}\">{1}</th>", headerStyle, (customAttr as DisplayNameAttribute).DisplayName);
            }
            break;
          }
        }

      }

由于链接的扩展方法无论如何都使用反射,您可以像上面一样修改 Header-Formatting 循环。

属性的用法如下所示:

public class Person {
    [DisplayName("First Name")]
    public string FirstName {
      get; set;
    }

    [DisplayName("Last Name")]
    public string LastName {
      get; set;
    }
    public int Age {
      get; set;
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 2012-06-08
    相关资源
    最近更新 更多