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))
精彩评论