2012-10-29 7 views
6
とカスタム属性を持つすべてのプロパティを取得します

可能性の重複:
How to get a list of properties with a given attribute?特定の値

は私がカスタムを持ってこの

public class ClassWithCustomAttributecs 
{ 
    [UseInReporte(Use=true)] 
    public int F1 { get; set; } 

    public string F2 { get; set; } 

    public bool F3 { get; set; } 

    public string F4 { get; set; } 
} 

などのカスタムクラスを持っています属性UseInReporte

[System.AttributeUsage(System.AttributeTargets.Property ,AllowMultiple = true)] 
public class UseInReporte : System.Attribute 
{ 
    public bool Use; 

    public UseInReporte() 
    { 
     Use = false; 
    } 
} 

いいえ私が取得したいすべてのプロパティ[UseInReporte(Use=true)]どのように私は反射を使用してこれを行うことができますか?もちろんtypeof(ClassWithCustomAttributecs)

答えて

11
List<PropertyInfo> result = 
    typeof(ClassWithCustomAttributecs) 
    .GetProperties() 
    .Where(
     p => 
      p.GetCustomAttributes(typeof(UseInReporte), true) 
      .Where(ca => ((UseInReporte)ca).Use) 
      .Any() 
     ) 
    .ToList(); 

おかげで、あなたが扱っている実際のオブジェクトに置き換える必要があります。

+1

これがどのように '[UseInReporte(Use = true)] 'を処理するか分かりません。 –

+0

親愛なる友人に感謝します。私はどのように 'Use == true'プロパティを得ることができますか? – Arian

+0

@JonB、良い点、ありがとう。アップデート – Andrei