【问题标题】:What makes the CLR show Assertions?是什么让 CLR 显示断言?
【发布时间】:2010-10-08 21:09:48
【问题描述】:

如果我在 Visual Studio 中为我的 C# 项目定义 Debug 常量,我可以确定断言将被评估并在它们失败时显示一个消息框。但是什么标志、属性使 CLR 在运行时实际上决定是否评估和显示断言。定义 DEBUG 时,断言代码是否不会在 IL 中结束?还是程序集的 DebuggableAttribute 中的DebuggableAttribute.DebuggingModes 标志是关键点?如果是这样,它必须存在什么枚举值?这在后台是如何工作的?

【问题讨论】:

    标签: .net debugging clr assertions


    【解决方案1】:

    System.Diagnostics.Debug 类的方法和 DEBUG 定义的 ConditionalAttribute。

    【讨论】:

      【解决方案2】:

      如果您在未定义 DEBUG 预处理器符号的情况下进行编译,则任何对 Debug.Assert 的调用都将从编译的代码中省略。

      如果您查看docs for Debug.Assert,您会发现它的声明中有[ConditionalAttribute("DEBUG")]ConditionalAttribute 用于决定是否在编译时实际发出方法调用。

      如果条件属性意味着未进行调用,则任何参数评估也将被忽略。这是一个例子:

      using System;
      using System.Diagnostics;
      
      class Test
      {
          static void Main()
          {
              Foo(Bar());
          }
      
          [Conditional("TEST")]
          static void Foo(string x)
          {
              Console.WriteLine("Foo called");
          }
      
          static string Bar()
          {
              Console.WriteLine("Bar called");
              return "";
          }
      }
      

      定义 TEST 时,两个方法都会被调用:

      c:\Users\Jon> csc Test.cs /d:TEST
      c:\Users\Jon> test.exe
      Bar called
      Foo called
      

      当没有定义 TEST 时,也不会调用:

      c:\Users\Jon> csc Test.cs /d:TEST
      c:\Users\Jon> test.exe
      

      【讨论】:

        猜你喜欢
        • 2010-12-06
        • 2017-12-12
        • 2013-02-25
        • 1970-01-01
        • 2012-03-13
        • 2020-04-07
        • 1970-01-01
        • 2011-01-21
        • 1970-01-01
        相关资源
        最近更新 更多