简体   繁体   English

如何在Visual Studio 2010中有条件地执行一行?

[英]How do I execute a line conditionally in Visual Studio 2010?

I'd like the line to execute when running within Visual Studio but not when the exe is running stand alone. 我想在Visual Studio中运行时执行该行,而不是在exe运行时独立运行。

Thanks. 谢谢。

Do you mean when a debugger is attached? 你是说连接调试器吗? If so, you could do something like this: 如果是这样,你可以这样做:

#if DEBUG
if (Debugger.IsAttached)
{
    //Your code here
}
#endif

This will only run when the debugger is attached, such as running with F5. 这仅在附加调试器时运行,例如使用F5运行。 Double clicking it or using Ctrl+F5 won't cause the if statement to be hit. 双击它或使用Ctrl + F5不会导致命中if语句。 It's also wrapped in a conditional so then when you compile to release the code is not even there. 它也包含在一个条件中,所以当你编译发布时,代码甚至不存在。

You could use the build flags 您可以使用构建标志

#if DEBUG
      //do something in here
#endif

And then when you build in release those things won't happen. 然后当你构建发布时,这些事情就不会发生。

You can use ConditionalAttribute . 您可以使用ConditionalAttribute Put the code you want to execute conditionally in a method, and mark the method with [Conditional("DEBUG")] . 将要执行的代码有条件地放在方法中,并使用[Conditional("DEBUG")]标记方法。 The method and the call to it will only be compiled when the DEBUG constant is set. 只有在设置了DEBUG常量时才会编译该方法和对它的调用。

I think this code may help: 我认为此代码可能有所帮助:

[Conditional("DEBUG")]
private void DEBUG_Execute() 
{ 
    if (Debugger.IsAttached)
    { 
        //todo:  execute line when running within VS
    } 
} 

You can check the Application.startuppath 您可以检查Application.startuppath

If you are in Debugging, that means bin/Debug folders are present otherwise you are running the exe. 如果您在调试中,这意味着存在bin / Debug文件夹,否则您正在运行exe。 In this way you can formulate the code. 通过这种方式,您可以制定代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM