Skip to main content
 首页 » 编程设计

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

2024年02月05日15duanxz

我将遍历 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;