当我不知道类型时,我可以获取 属性 的 DataAnnotation 显示名称吗?

Can I get the DataAnnotation Display Name of a property when I don't know the type?

我将遍历 ICollection 中项目的属性,在编译时不一定知道 ICollection 中项目的类型。我可以获得 属性 名称,但想要获取 DataAnnotation 显示名称(如果有)。

如何在 运行 时找到未知类型的 DataAnnotations(如果有)中定义的显示名称?

到目前为止我有这个:

foreach (var thisSection in Report.ReportSections)
{
    reportBody.Append(thisSection.ReportSectionName + Environment.NewLine);

    if (thisSection.ReportItems != null)
    {
        var itemType = thisSection.ReportItems.GetType().GetGenericArguments().Single();

        var first = true;
        foreach (var prop in itemType.GetProperties())
        {
            if (!first) reportBody.Append(",");

            // This gives me the property name like 'FirstName'
            reportBody.Append(prop.Name); 

            try
            {
                // I'd like to get the Display Name from 
                // [Display(Name = "First Name")]
                var displayName = prop.GetCustomAttributes();
            }
            catch (Exception e)
            {

            }

            first = false;
        }
        reportBody.Append(Environment.NewLine);
    }
}

ReportSection 定义如下:

public interface IReportSection
{
    string ReportSectionName { get; }

    ICollection ReportItems { get; }
}

ICollection 可以包含这样的对象集合:

public class ProjectAffiliateViewModel
{
    public string Role { get; set; }

    [Display(Name = "First Name")]
    public string FirstName { get; set; }
}

对于 Role 属性 我们会得到 Role,对于 FirstName 属性 我们会得到 First Name

像这样:

DisplayAttribute attribute = prop.GetCustomAttributes(typeof(DisplayAttribute), false)
                                 .Cast<DisplayAttribute>()
                                 .SingleOrDefault();

string displayName = (attribute != null) ? attribute.Name : prop.Name;