是什么让CLR显示断言?

时间:2009-02-20 16:10:02

标签: .net debugging clr assertions

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

2 个答案:

答案 0 :(得分:5)

如果在未定义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

答案 1 :(得分:2)

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