具有属性反射问题的对象

Object with properties Reflection Issue

我遇到了以下情况,我有一个对象 class 具有多个属性。
该对象将不止一次用于报告目的,但并非所有属性都是必需的,因此我正在考虑使用属性和反射以便能够在需要时获得所需的属性(用于显示绑定目的)(而不是硬编码要使用的字段)。我想使用属性和反射来获得以下功能

我的想法如下: - 在每个 属性 上设置 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);
            }
        }