【问题标题】:How select some of property of a Class by custom attribute如何通过自定义属性选择类的某些属性
【发布时间】:2012-07-30 14:26:06
【问题描述】:

我有一个 3 属性的类。

class Issuance
{
    [MyAttr]
    virtual public long Code1 { get; set; }

    [MyAttr]
    virtual public long Code2 { get; set; }

    virtual public long Code3 { get; set; }
}

我需要通过我的自定义属性([MyAttr])选择这个类中的一些属性。

我使用 GetProperties() 但这会返回所有属性。

var myList = new Issuance().GetType().GetProperties();
//Count of result is 3 (Code1,Code2,Code3) But count of expected is 2(Code1,Code2) 

我该怎么做?

【问题讨论】:

  • 您需要对每个属性使用 GetCustomAttributes 并检查返回的任何属性是否属于 MyAttr 类型。

标签: c# reflection attributes custom-attributes


【解决方案1】:

只需使用 LINQ 和使用 MemberInfo.IsDefined 的 Where 子句:

var myList = typeof(Issuance).GetProperties()
                             .Where(p => p.IsDefined(typeof(MyAttr), false);

【讨论】:

  • Jon 太棒了,我想我以前从未使用过 IsDefined - 这只是 GetCustomAttributes 的包装器吗?
  • @Charleh:我不知道——但使用起来肯定更简单:)
  • 我的问题解决了。当然,此示例代码需要在 LINQ 末尾添加 ToList()。
  • @Ehsan:如果你需要一个列表,它只需要ToList :) 如果你只是迭代属性,则不需要ToList 调用。
【解决方案2】:

http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getcustomattributes.aspx

试试这个 - 基本上对属性执行一次 foreach 并查看是否获取每个属性的属性类型。如果这样做,则该属性具有以下属性:

例如

foreach(var propInfo in new Issuance().GetType().GetProperties()) 
{
    var attrs = propInfo.GetCustomAttributes(typeof(MyAttr), true/false); // Check docs for last param

    if(attrs.Count > 0)
      // this is one, do something
}

【讨论】:

    猜你喜欢
    • 2017-11-07
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 2014-11-08
    相关资源
    最近更新 更多