我有一个定义为的类的对象列表
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
});
Run Code Online (Sandbox Code Playgroud)
并输出该列表作为具有属性名称作为列标题的表(完整源代码)
var propertyArray = typeof(T).GetProperties();
foreach (var prop in propertyArray)
result.AppendFormat("<th>{0}</th>", prop.Name);
Run Code Online (Sandbox Code Playgroud)
得到
FirstName | LastName | Age
----------------------------------
Alex Friedman 27
Run Code Online (Sandbox Code Playgroud)
我想要一些自定义标题,比如
First Name | Last Name | Age
Run Code Online (Sandbox Code Playgroud)
问题:如何为Person类的每个属性定义列标题?我应该在属性上使用自定义属性还是有更好的方法?
这是我针对你的情况采取的方法。这非常简单且不言自明:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
由于链接的扩展方法无论如何都使用反射,因此您只需像上面那样修改标头格式化循环即可。
该属性的用法如下所示:
public class Person {
[DisplayName("First Name")]
public string FirstName {
get; set;
}
[DisplayName("Last Name")]
public string LastName {
get; set;
}
public int Age {
get; set;
}
}
Run Code Online (Sandbox Code Playgroud)