class SomeModel
{
[Display(Name = "Quantity Required")]
public int Qty { get; set; }
[Display(Name = "Cost per Item")]
public int Cost { get; set; }
}我试图将模型映射到一个{ PropertyName, DisplayName }对列表中,但我遇到了困难。
var properties
= typeof(SomeModel)
.GetProperties()
.Select(p => new
{
p.Name,
p.GetCustomAttributes(typeof(DisplayAttribute),
false).Single().ToString()
}
);上面的代码不能编译,我不确定这是不是正确的方法,但希望你能看到它的意图。有什么建议吗?谢谢
发布于 2011-09-07 22:40:04
在这种情况下,您需要为匿名类型定义特定的属性名称。
var properties = typeof(SomeModel).GetProperties()
.Where(p => p.IsDefined(typeof(DisplayAttribute), false))
.Select(p => new
{
PropertyName = p.Name,
DisplayName = p.GetCustomAttributes(typeof(DisplayAttribute),
false).Cast<DisplayAttribute>().Single().Name
});https://stackoverflow.com/questions/7335629
复制相似问题