我得到了以下情况,我有一个对象类有多个属性。
该对象将不止一次用于报告目的,但并非所有属性都需要,因此我在考虑使用属性和反射,以便能够在需要时获得所需的属性(用于显示绑定目的)(而不是硬编码要使用的字段)。我想使用属性和反射来获得以下功能
我的想法是:-在每个属性上设置DisplayName属性(到目前为止一切顺利)—设置自定义属性(例如:useInReport1、useInReport2....)这将是每个属性上的布尔值)
我想知道我如何能够实现自定义属性[useInReport1], [useInReport2]等....+检索只需要的字段
我的对象的例子:
public class ReportObject
{
[DisplayName("Identity")]
[ReportUsage(Report1=true,Report2=true)]
public int ID {get {return _id;}
[DisplayName("Income (Euros)")]
[ReportUsage(Report1=true,Report2=false)]
public decimal Income {get {return _income;}
[DisplayName("Cost (Euros)")]
[ReportUsage(Report1=true,Report2=false)]
public decimal Cost {get {return _cost;}
[DisplayName("Profit (Euros)")]
[ReportUsage(Report1=true,Report2=true)]
public decimal Profit {get {return _profit;}
[DisplayName("Sales")]
[ReportUsage(Report1=false,Report2=true)]
public int NumberOfSales {get {return _salesCount;}
[DisplayName("Unique Clients")]
[ReportUsage(Report1=false,Report2=true)]
public int NumberOfDifferentClients {get {return _clientsCount;}
}
[System.AttributeUsage(AttributeTargets.Property,AllowMultiple=true)]
public class ReportUsage : Attribute
{
private bool _report1;
private bool _report2;
private bool _report3;
public bool Report1
{
get { return _report1; }
set { _report1 = value; }
}
public bool Report2
{
get { return _report2; }
set { _report2 = value; }
}
}
改写问题:我如何通过使用自定义属性示例获得属性列表:获取标记为Report1 = true的所有属性,以便读取其值等…
//Get all propertyes of class
var allProperties = typeof(ReportObject).GetProperties();
//List that will contain all properties used in specific report
List<PropertyInfo> filteredProperties = new List<PropertyInfo>();
foreach(PropertyInfo propertyInfo in allProperties) {
ReportUsage attribute = propertyInfo.GetCustomAttribute(typeof(ReportUsage), true) as ReportUsage;
if(attribute != null && attribute.ReportUsage1) { //if you need properties for report1
filteredProperties.Add(propertyInfo);
}
}