C#Attribute.isDefined()示例?

UpT*_*eek 10 c# metadata

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

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

Han*_*ant 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 { }
Run Code Online (Sandbox Code Playgroud)

  • 它非常不直观,Type类继承了MemberInfo.因此,IsDefined(MemberInfo,Type)重载可以完成工作.代码段已更新. (2认同)