在一个项目中,有一个类,它具有多个相似的属性名称。感兴趣的属性以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属性)。
答案 0 :(得分:3)
您可以使用反射。具体来说,GetProperties()
得到一个PropertyInfo
的数组-并由此而来的只是linq的Count
:
int GetReportDataPropertiesCount()
{
return typeof(ReportRowDataContract)
.GetProperties()
.Count(p => p.Name.StartsWith("ReportData"));
}