首页 > 解决方案 > 是否有可能只有在调试模式下编译的单行代码?

问题描述

请注意,我知道 Debug.Print - Console.WriteLine 是我正在尝试做的一个非常简化的示例。

有没有办法让一行代码只存在于 Debug 模式下,而根本不会出现在 Release 中?

我有一些命令可以帮助我调试对性能至关重要的代码部分的执行,并且我在关键位置的函数中放置了大量命令。

这是我所做的一个例子:

using System;
public class C {
    public Object _obj = new object();
    public void M() 
    {
        Alpha("This goes away in Release");
        Alpha(_obj.GetHashCode() + "...but this doesn't");

        #if DEBUG 
            //But I don't want this three line deal.
            Alpha(_obj.GetHashCode() + "...of course this does get removed");
        #endif

    }

    public static void Alpha(String s)
    {
        #if DEBUG
            Console.WriteLine(s);
        #endif
    }
}

问题是在发布模式下,编译器识别出第一个调用在发布模式下什么都不做,并将其删除。但它在第二次调用中没有这样做。I know this because I have tested it in SharpLab: https://sharplab.io/#v2:EYLgHgbALANALiAhgZwLYB8CQBXZBLAOwHMACAZQE9k4BTVAbgFgAoTAB22ABs8BjE3lxTISAYRIBvFpnace/APLAAVjV5wSAfQD2KkgF4SBGgHcSu1eoAUASiatZ3PiQBu2vABMSAWVslpmFIOmACCXGwAFohWAEQAKhF4IkTaNCKIJogUJIQkAEo0XDQoNDF2AaHhUVY6KgB0AOI0cAASKBGi2h40fgDUJDF1Q8DYGnCJIh6pyAQAAgC0AIxwZfYymBUAxHgAZiQAIgCiAEIAqg3+wZgA9NfHoyQAkiRTc0samQRjEyTjAE40GgkHjGF7FLh1CqVSLRWrKRrNNrIDpdHo2Ej9QZDbR7XjabB/ZBA8ZJF7TEhEZokAGobQuGgeVZbGgEDy7KEBAC+AQCHCc/GoiDgzjcnhIYRhVjIcD+hFIyBsASC622eyOZwaUM6BGQ2iKdQA6rLaAAZQg9BVrGSbFlsnZc6ScoA==

有没有办法避免三行版本?

标签: c#

解决方案


Yes, just put a [Conditional(...)] attribute on the method that you need to "not exist" unless you are using the Debug configuration:

[System.Diagnostics.Conditional("DEBUG")]
public static void Alpha(String s)
{
    Console.WriteLine(s);
}

All calls to such methods are effectively removed (not compiled) unless the specified symbol is present.

Note that a restriction applies: [Conditional(...)] can only be used for void methods.


推荐阅读