对象是否有属性

Does object have attribute

鉴于 class:

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

以及方法:

public static void Set(object objectToCache)
{

}

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

是:

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 将 return 给定对象具有的属性集合。然后检查是否有您想要的类型

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 的更多信息,正如 Александр Лысенко 所建议的那样,它似乎正是您要找的东西:

Returns true if one or more instances of attributeType or any of its derived types is applied to this member; otherwise, false.

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

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