获取具有特定值的自定义属性的所有属性

时间:2012-10-29 12:13:30

标签: c# c#-4.0 reflection attributes data-annotations

  

可能重复:
  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)]所有属性的所有属性如何使用反射来完成此操作?

感谢

1 个答案:

答案 0 :(得分:18)

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

当然typeof(ClassWithCustomAttributecs)应该替换为您正在处理的实际对象。

相关问题