开发者

C# Attribute.isDefined() example?

Can someone please give me an example of using Attribute.isDefined() to check if a particular custom attribute has been applied to a given class?

I've checked msdn, but only see possiblities for attributes applied to assemblies, members etc. I'm also open to alternative methods for achieving the same thing!开发者_JS百科


A simple example:

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 { }


There doesn't seem to be an overload of Attribute.IsDefined that takes a Type.

Instead, You can call Type.GetCustomAttributes:

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


The Type class inherits MemberInfo.
Therefore, you can use the overload that takes a MemberInfo:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜