c# - 检查自定义属性的方法

标签 c# custom-attributes late-binding

我不确定为什么下面的方法总是返回 false

        // method to check for presence of TestCaseAttribute
    private static bool hasTestCaseAttribute(MemberInfo m)
    {
        foreach (object att in m.GetCustomAttributes(true))
        {
            Console.WriteLine(att.ToString());
            if (att is TestCase.TestCaseAttribute) // also tried if (att is TestCaseAttribute)
            {
                return true;
            }
        }
        return false;

    }

即使控制台输出看起来像这样:

TestCase.DateAttribute
TestCase.AuthorAttribute
TestCase.TestCaseAttribute

我在这里错过了什么?

编辑;这种方法似乎有效...

  private static bool hasTestCaseAttribute(MemberInfo m)
    {
        if (m.GetCustomAttributes(typeof(TestCaseAttribute), true).Any())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

最佳答案

这应该可以解决问题。

    private static bool hasTestCaseAttribute(MemberInfo m)
    {
        return m.GetCustomAttributes(typeof(TestCaseAttribute), true).Any();
    }

关于c# - 检查自定义属性的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14554447/

相关文章:

c# - 如果设置了 AutoDeleteOnIdle,服务总线是否删除没有过滤器/规则的主题订阅?

c# - CefSharp WPF Web 浏览器未显示或呈现

C#: double 到长整型转换

c# - 具有多个 XmlArrayItemAttribute 实例的 GetCustomAttribute

r - 更改列表的 'names' 属性

c# - WPF OpenFileDialog 与 MVVM 模式?

来自 Properties 的 C# 自定义属性

c# - (自动)依赖注入(inject)绑定(bind)机制

c# - 如何动态加载包含非托管代码的原始程序集?(绕过 'Unverifiable code failed policy check' 异常)

java - 接口(interface)、抽象类和抽象类的方法