c# - 应用程序是否执行 Console.WriteLine ("Test");在编译版本?

标签 c# .net

我用了很多这样的台词

Console.WriteLine("Test");

在 VS 2010 下调试应用程序。

我的问题是:我在构建应用程序时是否对所有这些行都进行了注释?

谢谢!

最佳答案

是的。事实上,如果您的应用程序是控制台应用程序,您确实希望执行这些行。查看 System.Diagnostics.Debug 方法(例如 Debug.WriteLine ),这可能是您需要的。它们的输出在 Visual Studio 的输出窗口中,而在发布代码中它们什么也不做。

更一般地说,您可以通过执行以下操作获得仅在调试版本中编译的代码:

#if DEBUG
// Debug-only code here.
#endif

你也可以输入this attribute在您的方法定义之前编写一个在您进行发布构建时根本不会调用的方法:

    [System.Diagnostics.Conditional("DEBUG")]

所有这些方法的优点是它们不应影响生产代码的性能。

为了检查我给你的建议是否准确,我在 Release模式下编译了以下内容:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello world!");

#if DEBUG
        Console.WriteLine("Inside #if block.");
#endif

        WriteLine("With ConditionalAttribute.");

        Debug.WriteLine("Debug.WriteLine.");
    }

    [Conditional("DEBUG")]
    public static void WriteLine(string line)
    {
        Console.WriteLine(line);
    }
}

然后我使用 IL Dissasembler 工具查看实际运行的内容:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       11 (0xb)
  .maxstack  8
  IL_0000:  ldstr      "Hello world!"
  IL_0005:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_000a:  ret
} // end of method Program::Main

如您所见,仅调用了 Console.WriteLine 方法。正如我们所希望的,其他三个备选方案是从调试代码中“编译出来”的。

调试版本如下所示:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       46 (0x2e)
  .maxstack  8
  IL_0000:  nop
  IL_0001:  ldstr      "Hello world!"
  IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_000b:  nop
  IL_000c:  ldstr      "Inside #if block."
  IL_0011:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_0016:  nop
  IL_0017:  ldstr      "With ConditionalAttribute."
  IL_001c:  call       void ConditionalCompileTest.Program::WriteLine(string)
  IL_0021:  nop
  IL_0022:  ldstr      "Debug.WriteLine."
  IL_0027:  call       void [System]System.Diagnostics.Debug::WriteLine(string)
  IL_002c:  nop
  IL_002d:  ret
} // end of method Program::Main

关于c# - 应用程序是否执行 Console.WriteLine ("Test");在编译版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11333465/

相关文章:

c# - 创建一个可比较的字典键

c# - WebClient - 下载 json 作为字符串打破 json 的某种格式

c# - 条件运算符在 MVC Razor 中的某个地方运行不正常?

java - 这是哪个模板引擎?

c# - 具有大数据集的不完整 HttpWebResponse

.net - WinForms 应用程序中的自定义标题栏/镶边

c# - 使用 C++/CLI 从泛型函数返回泛型列表

c# - 在 C# 中添加对象到列表

C# .NET 2 Threading.Timer - 时间漂移

.net - 更改值时禁用 .NET 进度条动画?