对象是否有属性

本文关键字:属性 是否 对象 | 更新日期: 2023-09-27 18:15:08

给定类:

[ProtoContract]
[Serializable]
public class TestClass
{
    [ProtoMember(1)]
    public string SomeValue { get; set; }
}

方法:

public static void Set(object objectToCache)
{
}

是否可以检查objectToCache是否具有ProtoContract属性?

对象是否有属性

最简单的方法是使用以下代码:

public static void Set(object objectToCache)
{
    Console.WriteLine(objectToCache.GetType().IsDefined(typeof(MyAttribute), true));
}

是:

var attributes = TestClass.GetType().GetCustomAttributes(typeof(ProtoContract), true);
if(attributes.Length < 1)
    return; //we don't have the attribute
var attribute = attributes[0] as ProtoContract;
if(attribute != null)
{
   //access the attribute as needed
}

使用GetCustomAttributes,它将返回给定对象具有的属性集合。然后检查是否有你想要的类型

public static void Main(string[] args)
{
    Set(new TestClass());
}
public static void Set(object objectToCache)
{
    var result = objectToCache.GetType().GetCustomAttributes(false)
                                        .Any(att => att is ProtoContractAttribute);
    // Or other overload:
    var result2 = objectToCache.GetType().GetCustomAttributes(typeof(ProtoContractAttribute), false).Any();
    // result - true   
 }

阅读更多关于IsDefined Александр Лысенко建议它似乎是你正在寻找的:

如果一个或多个attributeType或其派生类型的实例应用于此成员,则返回true;否则,假的。