C# 检查元素是否具有属性

C# 检查元素是否具有属性,c#,generics,reflection,C#,Generics,Reflection,我试图创建一个扩展方法来检查特定对象是否具有特定属性 我发现了一个使用以下语法进行检查的示例: private static bool IsMemberTested(MemberInfo member) { foreach (object attribute in member.GetCustomAttributes(true)) { if (attribute is IsTestedAttribute) { return true;

我试图创建一个扩展方法来检查特定对象是否具有特定属性

我发现了一个使用以下语法进行检查的示例:

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);
    }

谢谢你们的帮助。现在我还有一个问题。假设我想用一个属性装饰类的一个属性,类型为string的属性,并想稍后检查该属性是否有属性。因为这只适用于类型,所以我不能在属性级别应用它。属性检查有什么解决方案吗?

您不能使用
类型
变量,因为
的参数是
运算符。此外,无需使用
Any
自行筛选,因为
GetCustomAttributes
的重载将为您完成此操作

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

内部静态AttributeType GetSingleAttribute(此类型),其中AttributeType:Attribute
{
var a=type.GetCustomAttributes(typeof(AttributeType),true);
return(AttributeType)a.SingleOrDefault();
}

您可以修改它以返回布尔值
a!=null
以获取所需内容。

不能使用
类型
变量,因为
的参数是
运算符。此外,无需使用
Any
自行筛选,因为
GetCustomAttributes
的重载将为您完成此操作

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

内部静态AttributeType GetSingleAttribute(此类型),其中AttributeType:Attribute
{
var a=type.GetCustomAttributes(typeof(AttributeType),true);
return(AttributeType)a.SingleOrDefault();
}

您可以修改它以返回布尔值
a!=null
来获取您想要的内容。

我已经提出了如何检查属性属性的解决方案,即使对于简单类型:

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

我已经就如何检查属性属性(即使是简单类型)提出了解决方案:

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

这是甜蜜的,我是用蛮力和无知的方式来做的。我刚把丹的分机改成了回传。返回type.GetCustomAttributes(typeof(TAttributeType),true).Any();这是甜蜜的,我是用蛮力和无知的方式来做的。我刚把丹的分机改成了回传。返回type.GetCustomAttributes(typeof(TAttributeType),true).Any();
    internal static AttributeType GetSingleAttribute<AttributeType>(this Type type) where AttributeType : Attribute
    {
        var a = type.GetCustomAttributes(typeof(AttributeType), true);
        return (AttributeType)a.SingleOrDefault();
    }
    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));