c# - 是否有可能只有在调试模式下编译的单行代码?
问题描述
请注意,我知道 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==
有没有办法避免三行版本?
解决方案
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.
推荐阅读
- c# - 提高 TableLayoutPanel 的性能 - C#
- applescript - 将项目移动到特定文件夹
- c# - ITextSharp 合并 PDF 异常
- python-3.x - 如何仅提取文章正文的某些部分?
- node.js - 如何使用 Nodejs 和 Rest API 打开 Excel 文件
- hyperledger - 锯齿可以用作无需许可的区块链吗?
- ionic3 - 类型“标头”缺少“标头”类型的以下属性:键、值、toJSON、getAll 和另外 2 个
- sql - 如何选择不同列值的最新记录?
- c++ - OpenGL、GLSL 片段着色器无法读取 Sampler2D 纹理
- scala - spark 按类型选择列