2012-10-29 146 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)]我如何使用反射来做到这一点?

感谢

回答

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

当然typeof(ClassWithCustomAttributecs)应该与你正在处理一个实际的对象替换。

+1

不知道如何处理'[UseInReporte(Use = true)]' –

+0

谢谢亲爱的朋友。我怎样才能得到'使用==真'的属性? – Arian

+0

@JonB,好点,谢谢。更新了答案 – Andrei