Mat*_*ith 85 c# debugging preprocessor
我想添加一些C#"仅调试"代码,只有在调试人员请求它时才会运行.在C++中,我曾经做过类似以下的事情:
void foo()
{
// ...
#ifdef DEBUG
static bool s_bDoDebugOnlyCode = false;
if (s_bDoDebugOnlyCode)
{
// Debug only code here gets executed when the person debugging
// manually sets the bool above to true. It then stays for the rest
// of the session until they set it to false.
}
#endif
// ...
}
Run Code Online (Sandbox Code Playgroud)
我不能在C#中完全相同,因为没有本地静态.
问题:在C#中实现这一目标的最佳方法是什么?
Kei*_*thS 135
实例变量可能是您想要的方式.您可以将其设置为静态以在程序的生命周期中保持相同的值(或者取决于您的静态内存模型的线程),或者使其成为普通实例var以在对象实例的生命周期内控制它.如果该实例是单例,则它们的行为方式相同.
#if DEBUG
private /*static*/ bool s_bDoDebugOnlyCode = false;
#endif
void foo()
{
// ...
#if DEBUG
if (s_bDoDebugOnlyCode)
{
// Code here gets executed only when compiled with the DEBUG constant,
// and when the person debugging manually sets the bool above to true.
// It then stays for the rest of the session until they set it to false.
}
#endif
// ...
}
Run Code Online (Sandbox Code Playgroud)
为了完成,pragma(预处理器指令)被认为是用来控制程序流的一点点..NET使用"条件"属性对此问题的一半具有内置答案.
private /*static*/ bool doDebugOnlyCode = false;
[Conditional("DEBUG")]
void foo()
{
// ...
if (doDebugOnlyCode)
{
// Code here gets executed only when compiled with the DEBUG constant,
// and when the person debugging manually sets the bool above to true.
// It then stays for the rest of the session until they set it to false.
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
没有pragma,更清洁.缺点是条件只能应用于方法,因此您必须处理在发布版本中不执行任何操作的布尔变量.由于该变量仅存在于从VS执行主机切换,并且在发布版本中它的值无关紧要,因此它非常无害.
小智 60
你在寻找什么
[ConditionalAttribute("DEBUG")]
Run Code Online (Sandbox Code Playgroud)
属性.
例如,如果您编写如下方法:
[ConditionalAttribute("DEBUG")]
public static void MyLovelyDebugInfoMethod(string message)
{
Console.WriteLine("This message was brought to you by your debugger : ");
Console.WriteLine(message);
}
Run Code Online (Sandbox Code Playgroud)
您在自己的代码中对此方法进行的任何调用都只能在调试模式下执行.如果在发布模式下构建项目,则甚至会调用"MyLovelyDebugInfoMethod"并将其从二进制文件中转储出来.
哦,还有一件事,如果您正在尝试确定您的代码当前是否正在执行时被调试,那么还可以检查当前进程是否被JIT挂钩.但这又是另一种情况.如果您正在尝试这样做,请发表评论.
Wes*_*Wes 20
如果在将流程附加到调试器时只需要运行代码,则可以尝试此操作.
if (Debugger.IsAttached)
{
// do some stuff here
}
Run Code Online (Sandbox Code Playgroud)
我认为可能值得一提的[ConditionalAttribute]
是System.Diagnostics;
命名空间。当我得到以下信息时,我有点绊倒:
Error 2 The type or namespace name 'ConditionalAttribute' could not be found (are you missing a using directive or an assembly reference?)
第一次使用它后(我以为它会在System
)。
如果你想知道是否在调试,程序中到处都是。用这个。
声明全局变量。
bool isDebug=false;
Run Code Online (Sandbox Code Playgroud)
创建用于检查调试模式的函数
[ConditionalAttribute("DEBUG")]
public static void isDebugging()
{
isDebug = true;
}
Run Code Online (Sandbox Code Playgroud)
在初始化方法中调用该函数
isDebugging();
Run Code Online (Sandbox Code Playgroud)
现在在整个程序中。您可以检查调试并进行操作。希望这可以帮助!