簡體   English   中英

檢查元素是否具有屬性

[英]Check if element has attribute

我正在嘗試創建擴展方法,以檢查特定對象是否具有特定屬性。

我找到了使用以下語法對其進行檢查的示例:

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

感謝您的幫助。 現在我有另一個問題。 假設我想用一個屬性來裝飾類的屬性(字符串類型的屬性),並希望稍后檢查該屬性是否具有屬性。 由於這僅適用於類型,因此無法將其應用於屬性級別。 財產檢查有什么解決辦法嗎?

您不能將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來獲取所需的內容。

我已經就如何檢查屬性屬性(甚至是簡單類型)提出了解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM