asp.net core如何让代码段只运行在 Debug 模式下?

咨询区

  • Ronnie Overby

我的 asp.net core 项目需要访问一个站外的 api 接口,双方协商通过api参数来约定当前请求是 测试 还是 正式, 目前的做法就是在测试环境中放开测试代码,在发布环境再注释掉这段代码,作为极客,我想知道有什么极简或者自动化的方式帮我判断呢?.

回答区

  • Dariusz Woźniak

这种多条件的解决方案太多了,我列几种可供你参考。

  1. Conditional 特性

这个特性会告诉编译器除非遇到指定的编译符号,否则将会被忽略,参考下面的例子:

static void Main(string[] args)
{
    [Conditional("DEBUG")]
    static void Method() { }

    Method();
}

  1. #if 预处理指令

当你用了  #if ... #end if 成对预处理指定时,当遇到编译符号与定义的环境一致时将会执行此if。

#if DEBUG
    static int testCounter = 0;
#endif 

需要提醒一下,这个预处理指令不像 C, C++ 那种可以带逻辑条件, C# 中的if预处理指令只能是一种 boolean 型表达式。

  1. Debug.Write 方法

Debug.Write 或 Debug.WriteLine 语句它可以将debug信息写入到 Trace Listeners 监听器下。

Debug.Write("Something to write in Output window.");

最后稍微提醒一下,使用 #if 预处理指令时在特定环境下对变量的赋值一定要记得多测试,比如下面的场景。

    string sth = null;

#if DEBUG
    sth = "oh, hi!";
#endif
    
    Console.WriteLine(sth);

如果当前是 Debug 环境,那么 str = oh, hi,如果为 Release 环境,那么 str=null,在某些情况下可能会造成 NullReferenceException 异常。

  • James Hulse

我也有同样的问题,不过我是通过 Diagnostics 下的 IsAttached 属性判断的。

if (System.Diagnostics.Debugger.IsAttached)
{
    // Code here
}

属性解释如下:

        //
        // Summary:
        //     Gets a value that indicates whether a debugger is attached to the process.
        //
        // Returns:
        //     true if a debugger is attached; otherwise, false.
        public static bool IsAttached
        {
            get
            {
                throw null;
            }
        }

只需要判断是否被调试器附加了就可以执行特定代码,完美。

点评区

Dariusz Woźniak 大佬提供的几种方式早有耳闻,后面这位大佬提供的方法让我耳目一新,学习了。