C# 对象是否具有属性

C# 对象是否具有属性,c#,object,attributes,protobuf-net,C#,Object,Attributes,Protobuf Net,鉴于班级: [ProtoContract] [Serializable] public class TestClass { [ProtoMember(1)] public string SomeValue { get; set; } } 方法是: public static void Set(object objectToCache) { } 是否可以检查objectToCache是否具有属性ProtoContract?是: var attributes = TestCla

鉴于班级:

[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
}
var attributes=TestClass.GetType().GetCustomAttributes(typeof(ProtoContract),true);
如果(attributes.Length<1)
返回//我们没有这个属性
var attribute=作为协议的属性[0];
if(属性!=null)
{
//根据需要访问属性
}

使用
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   
 }

阅读更多关于
的内容,如Аччччччччччччччччч109

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


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

public static void Set(object objectToCache)
{
    Console.WriteLine(objectToCache.GetType().IsDefined(typeof(MyAttribute), true));
}
objectToCache.GetType().GetCustomAttributes()
或其变体。