2015-09-07 93 views
0

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

我脑子里想的是什么如下: - 在每个属性中设置的显示名称属性(到目前为止好) - 设置自定义属性(例如:useInReport1,useInReport2 ....这将是每个属性上的布尔值)

我想知道我如何能够实现自定义属性[useInReport1],[useInReport2] etc .... +检索该字段只需要

我的对象示例:

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; } 
    } 

} 

的改写问:我怎样使用自定义属性的例子得到的属性列表:得到这是为了阅读他们的价值等功能标签为报表= true的属性...

+0

好,你有多远?你有没有声明属性类? (这些是属性,而不是属性 - 保持术语的直观性非常有帮助。)您是否尝试将这些属性应用于属性?你有没有试过检查哪些属性应用了属性?我们不会为你写整个解决方案 - 请告诉你卡在哪里。 –

+0

问一个更好的问题是,如果他甚至困扰在该地区远程搜索任何东西:) http://stackoverflow.com/questions/2281972/how-to-get-a-list-of-properties-with -a-given-attribute –

+0

感谢eran otzap。看着它,它会解决我的问题:)编辑帖子,以便有属性类也。会让你知道这是否会解决这个问题,因为这是我第一次处理反思。 – IanCian

回答

0
 //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); 
      } 
     }