C#中的#ifdef


116

我想执行以下操作,但是使用C#而不是C ++

#ifdef _DEBUG
bool bypassCheck=TRUE_OR_FALSE;//i will decide depending on what i am debugging
#else
bool bypassCheck = false; //NEVER bypass it
#endif
c# 

还要检查这个出色的答案,它显示了如何通过项目文件(.csproj)根据条件添加调试符号。
马特

Answers:


162
#if DEBUG
bool bypassCheck=TRUE_OR_FALSE;//i will decide depending on what i am debugging
#else
bool bypassCheck = false; //NEVER bypass it
#endif

确保在构建属性中选中了用于定义DEBUG的复选框。


51

我建议您使用条件属性

更新:3.5年后

您可以这样使用#if示例从MSDN复制):

// preprocessor_if.cs
#define DEBUG
#define VC_V7
using System;
public class MyClass 
{
    static void Main() 
    {
#if (DEBUG && !VC_V7)
        Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && VC_V7)
        Console.WriteLine("VC_V7 is defined");
#elif (DEBUG && VC_V7)
        Console.WriteLine("DEBUG and VC_V7 are defined");
#else
        Console.WriteLine("DEBUG and VC_V7 are not defined");
#endif
    }
}

仅在排除部分方法时有用。

如果用于#if从编译中排除某些方法,那么您还必须从编译中排除调用该方法的所有代码(有时您可能会在运行时加载某些类,而找不到带有“查找所有引用”的调用方)。否则会出现错误。

另一方面,如果您使用条件编译,您仍然可以保留所有调用该方法的代码。所有参数仍将由编译器验证。该方法只是在运行时不会调用。我认为最好只隐藏一次该方法,而不必同时删除调用它的所有代码。不允许在返回值的方法上使用条件属性-仅在void方法上使用。但是我认为这不是一个很大的限制,因为如果您使用#if返回值的方法,则必须隐藏所有调用它的代码。

这是一个例子:

    //调用Class1.ConditionalMethod()会在运行时被忽略 
    //除非定义了DEBUG常量


    使用System.Diagnostics;
    类Class1 
    {
       [视情况而定(“ DEBUG”)]
       公共静态无效ConditionalMethod(){
          Console.WriteLine(“ Executed Class1.ConditionalMethod”);
       }
    }

摘要:

我将#ifdef在C ++中使用,但在C#/ VB中,我将使用Conditional属性。这样,您可以隐藏方法定义,而不必隐藏调用它的代码段。调用代码仍由编译器编译和验证,但是在运行时不会调用该方法。您可能要使用#if以避免依赖项,因为使用条件属性,您的代码仍会编译。


1
+1确实不错,但有局限性,例如当您尝试从条件方法返回值时(据我所知)。我认为,内联示例会有所帮助。
Hamish Grubijan

1
这也不会阻止代码被编译,只是不允许该代码。当您要删除依赖项等时,区别很重要。
Lee Louviere

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.