代码之家  ›  专栏  ›  技术社区  ›  backslash17

我如何才能介绍只在调试模式下执行的句子和代码行?

  •  3
  • backslash17  · 技术社区  · 15 年前

    我在wich有一个应用程序,我几乎需要随时更改代码(更改crytographic过程等),所以我的想法是每次更改时都激活所有调试参数和变量。我不想一直在注释和取消注释代码,所以我的问题是 只在调试模式下执行的简单代码行。 我怎么能做到?

    4 回复  |  直到 15 年前
        1
  •  9
  •   John Gietzen    15 年前

    您可以使用条件代码部分:

    #if DEBUG
        //Your code goes here.
    #endif
    

    或者,您可以使用 [Conditional("DEBUG")] 属性使发布版本中的整个函数归零。

    如:

    [Conditional("DEBUG")]
    private void YourFunction()
    {
    }
    
        2
  •  4
  •   Keith Adler    15 年前

    这是一个很好的参考资料。

    http://www.csharphelp.com/archives/archive36.html

    从源头上看,这是一个很好的例子:

    #if DEBUG
             Console.WriteLine("DEBUG is defined");
          #else
             Console.WriteLine("DEBUG is not defined");
          #endif
    
        3
  •  1
  •   Joren    15 年前

    两种主要的解决方案是预处理器指令和 Conditional attribute . 相关的预处理器指令的工作方式如下:

    #if DEBUG
    // Lines here are only compiled if DEBUG is defined, like in a Debug build.
    
    #else
    
    // Lines here are only compiled if DEBUG is not defined, like in a Release build.
    
    #endif
    

    条件属性应用于方法:

    [Conditional("DEBUG")]
    public void DoDebugOnly()
    {
        // Whatever
    }
    

    然后所有 电话 只有在定义了调试时才会编译到dodebugonly()。

    这两种方法也适用于任何其他预处理器标识符。trace是集成到Visual Studio中的另一个示例,但您定义的任何预处理器标识符都有效:

    #define FOO
    
    #if FOO
    // Lines here are only compiled if FOO is defined.
    
    #endif
    
        4
  •  0
  •   TrueWill    15 年前

    根据您要做的工作,您可能需要考虑日志框架,例如 log4net 或者 Logging Application Block .这些将允许您在代码中保留调试消息,但仅当外部配置文件要求时才输出这些消息。

    但是,如果您想添加/删除实际执行逻辑的代码,请使用其他答案。