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

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)] 属性的属性,我该如何使用反射实现呢?
谢谢。
1个回答

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

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


1
不确定这个如何处理 [UseInReporte(Use=true)] - Jon B
谢谢亲爱的朋友。我怎么能获取“Use == true”的属性? - Arian
@JonB,好观点,谢谢。已更新回答。 - Andrei
@Kerezo,请查看更新版本。 - Andrei
1
我会使用.Any()代替.Count() >= 1 - Oliver
@Kerezo,您是否需要获取具有Exact Type UseInReporte属性或其任何子类的属性? - Hamlet Hakobyan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接