只能在“打开”时才运行的“仅debugging”代码

我想添加一些C#“仅debugging”的代码,只有在debugging者请求它时才运行。 在C ++中,我曾经做过类似如下的事情:

void foo() { // ... #ifdef DEBUG static bool s_bDoDebugOnlyCode = false; if (s_bDoDebugOnlyCode) { // Debug only code here gets executed when the person debugging // manually sets the bool above to true. It then stays for the rest // of the session until they set it to false. } #endif // ... } 

我不能在C#中完全一样,因为没有本地静态。

问题 :在C#中完成此操作的最佳方法是什么?

  1. 我应该使用私人类静态字段与C#预处理器指令(#如果/#endif DEBUG)?
  2. 我应该使用Conditional属性(保存代码),然后使用私有类的静态字段( 包括C#预处理器指令#if /#endif DEBUG?)。
  3. 别的东西?

一个实例variables可能会做你想做的。 你可以使它成为静态的,以便在程序的整个生命周期中保持相同的值(或者依赖于你的静态内存模型的线程),或者使它成为一个普通的实例var来控制对象实例的生命周期。 如果这个实例是一个单例,那么它们的行为也是一样的。

 #if DEBUG private /*static*/ bool s_bDoDebugOnlyCode = false; #endif void foo() { // ... #if DEBUG if (s_bDoDebugOnlyCode) { // Code here gets executed only when compiled with the DEBUG constant, // and when the person debugging manually sets the bool above to true. // It then stays for the rest of the session until they set it to false. } #endif // ... } 

只是要完成,编译指示(预处理指令)被认为是一个用来控制程序stream程的混乱。 对于这个问题的一半,.NET有一个内置的答案,使用“Conditional”属性。

 private /*static*/ bool doDebugOnlyCode = false; [Conditional("DEBUG")] void foo() { // ... if (doDebugOnlyCode) { // Code here gets executed only when compiled with the DEBUG constant, // and when the person debugging manually sets the bool above to true. // It then stays for the rest of the session until they set it to false. } // ... } 

没有杂记,更干净。 缺点是条件只能应用于方法,所以你必须处理一个布尔variables,在发布版本中不做任何事情。 由于variables只能从VS执行主机切换,而在发布版本中,它的值并不重要,所以它是非常无害的。

你在找什么

 [ConditionalAttribute("DEBUG")] 

属性。

如果你例如写一个方法,如:

 [ConditionalAttribute("DEBUG")] public static void MyLovelyDebugInfoMethod(string message) { Console.WriteLine("This message was brought to you by your debugger : "); Console.WriteLine(message); } 

您在自己的代码中对此方法所做的任何调用只会在debugging模式下执行。 如果在发布模式下构build项目,则即使调用“MyLovelyDebugInfoMethod”也将被忽略并从您的二进制文件中剔除。

哦,还有一件事情,如果你正在试图确定你的代码是否在执行时正在被debugging,也可以检查当前进程是否被JIT挂钩。 但这是所有在一起的另一种情况。 发表评论,如果这是你正在做的事情。

你可以试试这个,如果你只需要运行代码的时候,你有一个debugging器连接到进程。

 if (Debugger.IsAttached) { // do some stuff here } 

如果你想知道是否在debugging,在程序中无处不在。 用这个。

声明全局variables。

 bool isDebug=false; 

创build检查debugging模式的function

 [ConditionalAttribute("DEBUG")] public static void isDebugging() { isDebug = true; } 

在初始化方法中调用该函数

 isDebugging(); 

现在在整个程序中。 您可以检查debugging并执行操作。 希望这可以帮助!

我认为可能值得一提的是[ConditionalAttribute]System.Diagnostics; 命名空间。 当我得到时,我偶然发现了一点:

Error 2 The type or namespace name 'ConditionalAttribute' could not be found (are you missing a using directive or an assembly reference?)

第一次使用它之后(我以为它会在System )。