11

可能重复:
如何获取具有给定属性的属性列表?

我有一个像这样的自定义类

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)]如何使用反射来执行此操作的属性?

谢谢

4

1 回答 1

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

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

于 2012-10-29T12:18:58.947 回答