Ron*_*rby 34 .net c# vb.net debugging visual-studio
我有一些代码可以访问网络上的API.API的参数之一允许我让他们知道我正在测试.
我想在测试时只在我的代码中设置此参数.目前,我只是在发布版本时对代码进行评论.
是否有基于构建配置的自动方式?
Dar*_*iak 92
您可以使用以下其中一项 -
Conditional属性该Conditional属性向编译器指示应忽略方法调用或属性,除非定义了指定的条件编译符号.
代码示例:
[Conditional("DEBUG")]
static void Method() { }
Run Code Online (Sandbox Code Playgroud)
#if预处理器指令当C#编译器遇到预处理程序指令,最后是#endif指令时,只有在定义了指定的符号时,它才会编译指令之间的代码.与C和C++不同,您无法为符号指定数值.C#中的#if语句是布尔值,仅测试符号是否已定义.#if
代码示例:
#if DEBUG
static int testCounter = 0;
#endif
Run Code Online (Sandbox Code Playgroud)
Debug.Write方法Debug.Write(和Debug.WriteLine)将有关调试的信息写入Listeners集合中的跟踪侦听器.
另见Debug.WriteIf和Debug.WriteLineIf.
代码示例:
Debug.Write("Something to write in Output window.");
Run Code Online (Sandbox Code Playgroud)
请注意使用#if指令,因为它可能会在发布版本中产生意外情况.例如,请参阅:
string sth = null;
#if DEBUG
sth = "oh, hi!";
#endif
Console.WriteLine(sth);
Run Code Online (Sandbox Code Playgroud)
在这种情况下,非Debug构建将打印空白消息.但是,这可能会NullReferenceException在不同情况下引发.
还有一个工具DebugView,它允许从外部应用程序捕获调试信息.
Mat*_*eer 31
是的,包装代码
#if DEBUG
// do debug only stuff
#else
// do non DEBUG stuff
#endif
Run Code Online (Sandbox Code Playgroud)
谷歌的"C#编译符号"
Visual Studio会自动定义DEBUG您何时处于调试配置中.您可以定义所需的任何符号(查看项目的属性,构建选项卡).请注意,滥用预处理程序指令是一个坏主意,它可能导致代码很难读取/维护.
Jam*_*lse 14
我有同样的问题,我使用的解决方案是使用:
if (System.Diagnostics.Debugger.IsAttached)
{
// Code here
}
Run Code Online (Sandbox Code Playgroud)
这意味着从技术上讲,您可以附加调试器并运行该段代码.
除#if #endif指令外,您还可以使用条件属性.如果使用属性标记方法
[Conditional("Debug")]
Run Code Online (Sandbox Code Playgroud)
只有在应用程序以调试模式构建时才会编译和运行它.正如下面的评论中所指出的,这些仅在方法具有void返回类型时才起作用.
这是另一篇具有类似结果的帖子:http://www.bigresource.com/Tracker/Track-vb-lwDKSoETwZ/
更好的解释可以参见:http ://msdn.microsoft.com/en-us/library/4y6tbswk.aspx
// preprocessor_if.cs
#define DEBUG
#define MYTEST
using System;
public class MyClass
{
static void Main()
{
#if (DEBUG && !MYTEST)
Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && MYTEST)
Console.WriteLine("MYTEST is defined");
#elif (DEBUG && MYTEST)
Console.WriteLine("DEBUG and MYTEST are defined");
#else
Console.WriteLine("DEBUG and MYTEST are not defined");
#endif
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25381 次 |
| 最近记录: |