C#Attribute.isDefined()示例?

时间:2010-06-11 19:55:48

标签: c# metadata

有人可以给我一个使用Attribute.isDefined()来检查特定自定义属性是否已应用于给定类的示例吗?

我已经检查了msdn,但只看到了应用于程序集,成员等的属性的可能性。我也对实现相同的东西的其他方法持开放态度!

3 个答案:

答案 0 :(得分:7)

一个简单的例子:

using System;
using System.Diagnostics;

[Foo]
class Program {
    static void Main(string[] args) {
        var ok = Attribute.IsDefined(typeof(Program), typeof(FooAttribute));
        Debug.Assert(ok);
    }
}

class FooAttribute : Attribute { }

答案 1 :(得分:2)

似乎没有Attribute.IsDefined的重载需要Type

相反,您可以致电Type.GetCustomAttributes

if (typeof(SomeClass).GetCustomAttributes(typeof(SomeAttribute), false).Length > 0)

答案 2 :(得分:1)

Type class继承MemberInfo 因此,您可以使用MemberInfo

overload
if (Attribute.IsDefined(typeof(SomeClass), typeof(SomeAttribute))