【问题标题】:Object with properties Reflection Issue具有属性反射问题的对象
【发布时间】:2015-09-07 09:33:48
【问题描述】:

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

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

【问题讨论】:

  • 嗯,你走了多远?你已经声明了属性类了吗? (这些是属性,而不是属性 - 保持术语直截了当真的很有帮助。)您是否尝试将这些属性应用于您的属性?您是否尝试过检查哪些属性应用了属性?我们不会只为您编写整个解决方案 - 请说明您遇到的问题。
  • 问他一个更好的问题是,他是否甚至在该区域远程搜索任何东西 :) stackoverflow.com/questions/2281972/…
  • 感谢eran otzap。正在查看它,它将解决我的问题:) 编辑帖子以便也具有属性类。会告诉你这是否能解决问题,因为这是我第一次处理反射。

标签: c# asp.net reflection


【解决方案1】:
        //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);
            }
        }

【讨论】:

    猜你喜欢
    • 2010-11-02
    • 2019-12-06
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 2010-10-29
    • 2013-10-08
    • 1970-01-01
    相关资源
    最近更新 更多