如何获取DataAnnotation显示名称?

Jam*_*123 6 c# data-annotations asp.net-mvc-4

我有EF模型类.因为我MetadataType为那个部分类创建了.

现在我需要从c#中读取或获取对象属性的所有这些displayname.所以我可以使用Excel Excel标题行.

[MetadataType(typeof(vwGridMetadata))]
public partial class vwGrid
{

}

public class vwGridMetadata
{
    [Display(Name = "Note ID")]
    public int intNoteID { get; set; }
    [Display(Name = "Global Number")]
    public string strGlobalLoanNumber { get; set; }
    [Display(Name = "Data Source ID")]
    public Nullable<int> intDataSourceID { get; set; }
    [Display(Name = "Sample ID")]
    ....
}
Run Code Online (Sandbox Code Playgroud)

vwGrid grd = new vwGrid;

在这里,我想在迭代中获取所有属性displayname.所以我可以将它们添加到excel Header行和单元格中.怎么做?

Sel*_*enç 12

Reflection并且LINQ是你的朋友

typeof(vwGridMetadata)
.GetProperties()
.Select(x => x.GetCustomAttribute<DisplayAttribute>())
.Where(x => x != null)
.Select(x => x.Name);
Run Code Online (Sandbox Code Playgroud)

注意:您需要在项目中包含System.ReflectionSystem.Linq命名空间才能使用这些方法.