I've been doing some performance testing around the use of System.Diagnostics.Debug, and it seems that all code related to the static class Debug gets completely removed when the Release configuration is built. I was wondering how the compiler knows that. Maybe there is some class or configuration attribute that allows to specify exactly that behavior.
我一直在使用System.Diagnostics.Debug进行一些性能测试,似乎所有与静态类Debug相关的代码在构建Release配置时都会被完全删除。我想知道编译器是如何知道的。也许有一些类或配置属性允许准确指定该行为。
I am trying to create some debugging code that I want completely removed from the Release configuration, and I was wondering if I could do it just like the Debug class where simply changing the configuration parameters removes the code.
我正在尝试创建一些我想要从Release配置中完全删除的调试代码,我想知道我是否可以像Debug类那样只需更改配置参数就可以删除代码。
3 个解决方案
#1
19
You can apply the ConditionalAttribute attribute, with the string "DEBUG" to any method and calls to that item will only be present in DEBUG builds.
您可以将带有字符串“DEBUG”的ConditionalAttribute属性应用于任何方法,并且对该项的调用将仅出现在DEBUG构建中。
This differs from using the #ifdef approach as this allows you to release methods for use by other people in their DEBUG configurations (like the Debug class methods in the .NET framework).
这与使用#ifdef方法不同,因为这允许您在其DEBUG配置中释放供其他人使用的方法(如.NET框架中的Debug类方法)。
#2
16
Visual Studio defines a DEBUG constant for the Debug configuration and you can use this to wrap the code that you don't want executing in your Release build:
Visual Studio为Debug配置定义了一个DEBUG常量,您可以使用它来包装您不希望在Release版本中执行的代码:
#ifdef DEBUG
// Your code
#endif
However, you can also decorate a method with a Conditional attribute, meaning that the method will never be called for non-Debug builds (the method and any call-sites will be removed from the assembly):
但是,您也可以使用Conditional属性修饰方法,这意味着永远不会为非Debug构建调用该方法(该方法和任何调用站点将从程序集中删除):
[Conditional("DEBUG")]
private void MyDebugMethod()
{
// Your code
}
#1
19
You can apply the ConditionalAttribute attribute, with the string "DEBUG" to any method and calls to that item will only be present in DEBUG builds.
您可以将带有字符串“DEBUG”的ConditionalAttribute属性应用于任何方法,并且对该项的调用将仅出现在DEBUG构建中。
This differs from using the #ifdef approach as this allows you to release methods for use by other people in their DEBUG configurations (like the Debug class methods in the .NET framework).
这与使用#ifdef方法不同,因为这允许您在其DEBUG配置中释放供其他人使用的方法(如.NET框架中的Debug类方法)。
#2
16
Visual Studio defines a DEBUG constant for the Debug configuration and you can use this to wrap the code that you don't want executing in your Release build:
Visual Studio为Debug配置定义了一个DEBUG常量,您可以使用它来包装您不希望在Release版本中执行的代码:
#ifdef DEBUG
// Your code
#endif
However, you can also decorate a method with a Conditional attribute, meaning that the method will never be called for non-Debug builds (the method and any call-sites will be removed from the assembly):
但是,您也可以使用Conditional属性修饰方法,这意味着永远不会为非Debug构建调用该方法(该方法和任何调用站点将从程序集中删除):
[Conditional("DEBUG")]
private void MyDebugMethod()
{
// Your code
}