C#中的#ifdef

时间:2009-06-10 12:49:10

标签: c#

我想在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

5 个答案:

答案 0 :(得分:159)

#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的复选框。

答案 1 :(得分:46)

我建议您使用Conditional Attribute

更新:3。5年后

您可以像这样使用#ifexample copied from 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方法返回一个值,你必须隐藏所有调用它的代码片段。

以下是一个例子:


    // calling Class1.ConditionalMethod() will be ignored at runtime 
    // unless the DEBUG constant is defined


    using System.Diagnostics;
    class Class1 
    {
       [Conditional("DEBUG")]
       public static void ConditionalMethod() {
          Console.WriteLine("Executed Class1.ConditionalMethod");
       }
    }

<强>要点:

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

答案 2 :(得分:43)

我认为

#if将成为你的新朋友。

如果要定义自己的自定义编译符号,可以在项目属性中执行此操作(在“构建”选项卡上;“条件编译符号”)。

答案 3 :(得分:1)

C#确实有一个预处理器。它的工作方式略有不同 C ++和C。

以下是MSDN链接 - all preprocessor directives上的部分。

答案 4 :(得分:0)

我能够通过将 <DefineConstants> 标记添加到 csproj 的 xml 中来实现该行为。

  1. 使用文本编辑器打开项目文件。
  2. 找到包含所有项目属性定义的第一个 <PropertyGroup>
  3. 在此群组中添加 <DefineConstants>SOME_VARIABLE_NAME</DefineConstants>
  4. #if SOME_VARIABLE_NAME 添加到您的代码以有条件地启用代码。
相关问题