C# 具有属性反射问题的对象

C# 具有属性反射问题的对象,c#,asp.net,reflection,C#,Asp.net,Reflection,我遇到了以下情况,我有一个对象类具有多个属性。 这个对象将不止一次地用于报告目的,但是并不需要所有属性,因此我考虑使用属性和反射,以便在需要时(而不是硬编码要使用的字段)能够获得所需的属性(用于显示绑定目的)。我想使用属性和反射来获得以下功能 我的想法如下: -在每个属性上设置DisplayName属性(到目前为止还不错) -设置自定义属性(例如:useInReport1、useInReport2…每个属性上都是布尔值) 我想知道如何实现自定义属性[useInReport1]、[useInRep

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

我的想法如下: -在每个属性上设置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的所有属性,以便读取它们的值等。

//获取类的所有属性yes
        //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);
            }
        }
var allProperties=typeof(ReportObject).GetProperties(); //包含特定报告中使用的所有属性的列表 List filteredProperties=新列表(); foreach(所有属性中的PropertyInfo PropertyInfo){ ReportUsage attribute=propertyInfo.GetCustomAttribute(typeof(ReportUsage),true)作为ReportUsage; if(attribute!=null&&attribute.ReportUsage1){//如果需要report1的属性 filteredProperties.Add(propertyInfo); } }
那么,你已经走了多远?您已经声明了属性类了吗?(这些是属性,而不是属性-保持术语的直截了当非常有帮助。)您是否尝试过将这些属性应用于您的属性?您是否尝试过检查哪些属性应用了属性?我们不会只为你写完整的解决方案——请指出你的困境所在。问他一个更好的问题是,他是否在那个区域远程搜索过任何东西:)谢谢埃兰·奥扎普。我正在看它,它将解决我的问题:)编辑文章,以便也有属性类。将让您知道这是否会解决问题,因为这是我第一次处理反射。