如何使调试与发布之间的编译不同?
我是 C# 新手,在编译 C# 项目时遇到问题。这是关于调试和发布模式下的调试日志。 我希望在 Debug 模式下调用 log 函数,但在 Release 模式下不调用,考虑到性能。 我知道在C/C++中,这很容易做到:
// this is C/C++ sample, not C#
#ifdef DEBUG
#define DebugLog(CString,__VA_ARGS__) LogFunction(CString,__VA_ARGS__)
#else
#define DebugLog
#endif
在上面的C/C++代码中,DebugLog()是在Debug模式下编译和调用的,但在Release模式下不编译和调用,因此可以保证性能。
C# 中是否有与上述 C/C++ 代码类似的工作方式?
I'm a newbee to C#, and encounter a problem when compiling a C# project. It's about debug log in Debug and Release modes.
I want the log function to be called in Debug mode, but not called in Release mode, taking performance into account.
I know in C/C++, this is easy to be done:
// this is C/C++ sample, not C#
#ifdef DEBUG
#define DebugLog(CString,__VA_ARGS__) LogFunction(CString,__VA_ARGS__)
#else
#define DebugLog
#endif
In the above C/C++ code, the DebugLog() is compiled and called in Debug mode, but not compiled or called in Release mode, so the performance can be ensured.
Is there anyway in C# that works like the above C/C++ codes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 C# 中,您可以执行
以下操作:这是参考文档 用于
#if
指令。In C# you can do
Here's the reference documentation for the
#if
directive.等效的是方法上的 [Conditional] 属性。像这样:
在Release构建中(未定义DEBUG),方法和对方法的调用都被编译器删除。在重新发明这个轮子之前,请务必查看 .NET 框架中的 Debug 和 Trace 类,它们已经做到了这一点。并且具有很大的灵活性来重定向调试/跟踪信息。
The equivalent is the [Conditional] attribute on a method. Like this:
In the Release build (with DEBUG not defined), both the method and the calls to the method are removed by the compiler. Before you re-invent this wheel, be sure to review the Debug and Trace classes in the .NET framework, they already do this. And have lots of flexibility to redirect the debug/trace info.
您可以在 C# 中执行相同的操作。在项目属性中,您可以设置条件编译符号,例如
DEBUG
。事实上,我认为 Visual Studio 在创建项目时默认会执行此操作 - 当项目处于调试模式时,它会添加一个 DEBUG 标志,并在切换到发布模式时删除该标志。这可以在“项目属性”->“构建”选项卡中进行配置。您还可以为特定于平台的代码等内容添加自己的标志。Pocket_PC
标志因在 .NET Compact Framework 上进行老式 Windows Mobile 开发而闻名。这样,您可以添加预处理器指令,如下所示:
You can do the same thing in C#. In the project properties, you can set a conditional compilation symbol like
DEBUG
. In fact, I think Visual Studio will do this by default when you create a project - it will add aDEBUG
flag when the project is in Debug mode, and remove the flag when you switch to Release mode. This can be configured in the Project Properties->Build tab. You can also add your own flags for things like platform-specific code. ThePocket_PC
flag was a famous one for doing old-school Windows Mobile development on the .NET Compact Framework.With this, you can add the pre-processor directives like this:
其他方法,可以包含“条件”属性,例如
更多信息可以在 此处找到在 MSDN 中
Other methodology, can include a "Conditional" attribute like
More informations can be found here in MSDN