检查元素是否具有属性

时间:2012-10-25 12:15:33

标签: c# generics reflection

我正在尝试创建扩展方法,以检查特定对象是否具有特定属性。

我找到了使用以下语法检查它的示例:

private static bool IsMemberTested(MemberInfo member)
{
foreach (object attribute in member.GetCustomAttributes(true))
    {
        if (attribute is IsTestedAttribute)
        {
           return true;
        }
    }
return false;
}

现在我正在尝试执行以下操作:

    public static bool HasAttribute<T>(this T instance, Type attribute)
    {
        return typeof(T).GetCustomAttributes(true).Any(x => x is attribute);
    }

但是我收到消息'类型或名称空间'属性'缺失...'

我做错了什么,与给定的例子不同/我该如何实现?

编辑:

感谢您的提示,我现在已经设法做到了这一点:

    public static bool HasAttribute<T>(this T instance, Type attribute)
    {
        return typeof(T).GetCustomAttributes(attribute, true).Any();
    }

检查属性是这样的:

var cc = new CustomClass();
var nullable = cc.HasAttribute(typeof(NullableAttribute));

谢谢你的帮助。现在我有另一个问题。假设我想要使用属性装饰类的属性,类型为string的属性,并且想要稍后检查该属性是否具有属性。由于这只适用于类型,我不能在属性级别上应用它。有没有财产检查的解决方案?

2 个答案:

答案 0 :(得分:3)

您不能使用Type变量作为is运算符的参数。此外,您无需使用Any自行过滤,因为GetCustomAttributes会超载,可以为您完成。

我已经为类似的功能编写了这个扩展方法(我的目的是返回应用于类的单个属性):

    internal static AttributeType GetSingleAttribute<AttributeType>(this Type type) where AttributeType : Attribute
    {
        var a = type.GetCustomAttributes(typeof(AttributeType), true);
        return (AttributeType)a.SingleOrDefault();
    }

你可以修改它以返回一个布尔值a != null,而不是得到你想要的东西。

答案 1 :(得分:0)

我已经解决了如何检查属性属性的问题,即使对于简单类型:

    public static bool HasPropertyAttribute<T>(this T instance, string propertyName, Type attribute)
    {
        return Attribute.GetCustomAttributes(typeof(T).GetProperty(propertyName), attribute, true).Any();
    }

调用是这样的:

var cc = new CustomClass();
cc.HasPropertyAttribute("Name", typeof(NullableAttribute));