需要.NET代码才能在调试配置时执行 [英] Need .NET code to execute only when in debug configuration
问题描述
当我测试时,我只想在我的代码中设置这个参数。目前,我只是在发布版本时将代码评论。
有没有一种基于构建配置的自动方法?
1:您可以使用 条件
属性:
[Conditional(DEBUG)]
static void Method(){}
#if DEBUG
static int testCounter = 0;
#endif
3:或 Debug.Write
\ Debug.WriteLine
方法:
Debug.Write(在输出窗口中写入的东西);
小心使用#如果
指令,因为它可能会在版本构建中产生意外的情况。例如,请参阅:
string sth = null;
#if DEBUG
sth =哦,嗨!;
#endif
Console.WriteLine(sth);
在这种情况下,非调试版本将打印一个空白消息。
阅读更多:
- Eric Lippert。 有什么区别?条件编译和条件属性?
- C#程序员参考:条件方法教程
- Bill Wagner。 有效的C#:50个具体的方法来改善你的C#(书),章节:使用条件属性而不是#if
- John Robbins。 .NET中的断言和跟踪
<李三安
还有一个工具, DebugView ,允许捕获调试来自外部应用程序的信息。
I have some code that access an API out on the web. One of the API's parameters allows me to let them know that I am testing.
I would like to only set this parameter in my code when I am testing. Currently, I just comment the code out when I do a release build.
Is there an automatic way of doing this based on the build configuration?
1: You can use Conditional
attribute:
[Conditional("DEBUG")]
static void Method() { }
2: #if
preprocessor directive:
#if DEBUG
static int testCounter = 0;
#endif
3: Or Debug.Write
\ Debug.WriteLine
method:
Debug.Write("Something to write in Output window.");
Beware of using #if
directive since it can produce unintended situations in Release build. For example, see:
string sth = null;
#if DEBUG
sth = "oh, hi!";
#endif
Console.WriteLine(sth);
In this case, non-Debug build will print a blank message.
Read more:
- Eric Lippert. What's the difference between conditional compilation and the conditional attribute?
- C# Programmer's Reference: Conditional Methods Tutorial
- Bill Wagner. Effective C#: 50 Specific Ways to Improve Your C# (book), chapter: Use Conditional Attributes Instead of #if
- John Robbins. Assertions and Tracing in .NET
- Sam Allen. Dot Not Perls
There is also a tool, DebugView, which allow to capture debug information from external applications.
这篇关于需要.NET代码才能在调试配置时执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!