【问题标题】:check method for custom attribute自定义属性的检查方法
【发布时间】:2013-01-28 01:58:14
【问题描述】:

我不确定为什么下面的方法总是返回 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;
        }
    }

【问题讨论】:

    标签: c# custom-attributes late-binding


    【解决方案1】:

    这应该可以解决问题。

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

    【讨论】:

      【解决方案2】:
      public static bool HasCustomAttribute(MethodInfo methodInfo, bool inherit = false)
      {
          return methodInfo.GetCustomAttribute<CustomAttribute>(inherit) != null;
      }
      

      您可以使用上面的函数,它比您当前的方法更简洁。 sa_ddam 的 sn-p 也可以。

      【讨论】:

      • 感谢 ByteBlast!请参阅我的编辑,了解我是如何合并的。如果您认为我应该做一些不同的事情,请随时发表评论。
      • 不用担心。您不需要繁琐的if else statement。 else 是多余的,因为如果满足第一个条件,该方法将 return 将控制权返回给调用地址。函数GetCustomAttributes 已经返回一个布尔值,所以你根本不需要任何条件检查。就像我在示例中所做的那样,简单地回显函数返回的值。
      • 你知道,我试过了,但仍然得到一个错误的值。我使用这个方法作为检查,以确保在调用它之前该属性存在于 MethodInfo 对象中,所以我需要确保我可以获得 true 或 false。
      • 我描述的重构不应该影响这样的事情:/
      【解决方案3】:

      你可以试试这个:

      private static bool hasTestCaseAttribute(MethodInfo method)
      {    
          object[] customAttributes = Attribute.GetCustomAttribute(method, 
                                          typeof(TestCase), true) as TestCase;
          if(customAttributes.Length>0 && customAttributes[0]!=null)
          {
              return true;
          }
          else
          {
              return false;
          }
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-09
        • 1970-01-01
        • 2014-12-02
        • 2011-01-19
        • 2017-06-21
        相关资源
        最近更新 更多