计算遵循特定命名约定的类中的属性

时间:2018-12-09 13:12:56

标签: c#

在一个项目中,有一个类,它具有多个相似的属性名称。感兴趣的属性以ReportData开头。有没有办法修改GetReportDataFieldCount方法,以便它自动计算以ReportData开头的类中的属性数量?

public class ReportRowDataContract
{   
    public ReportDataDataContract ReportData1 { get; set; }

    public ReportDataDataContract ReportData2 { get; set; }

    public ReportDataDataContract ReportData3 { get; set; }

    public ReportDataDataContract ReportData4 { get; set; }

    public ReportDataDataContract ReportData5 { get; set; }

    public ReportDataDataContract ReportData6 { get; set; }

    // an indexed property - for accessing report data fields by index
    public ReportDataDataContract this[int i]
    {
        get
        {
            return new ReportDataDataContract[]
            {
              ReportData1,
              ReportData2,
              ReportData3,
              ReportData4,
              ReportData5,
              ReportData6                  
            }[i];
        }
    }

    public int GetReportDataFieldCount()
    {
        return 6;
    }        
}

请注意,我无法更改此类的结构(即,顺序编号的ReportData属性)。

1 个答案:

答案 0 :(得分:3)

您可以使用反射。具体来说,GetProperties()得到一个PropertyInfo的数组-并由此而来的只是linq的Count

int GetReportDataPropertiesCount()
{
    return typeof(ReportRowDataContract)
        .GetProperties()
        .Count(p => p.Name.StartsWith("ReportData"));
}