【问题标题】:Conditional Compiling - Phasing out Part of code in C#条件编译 - 逐步淘汰 C# 中的部分代码
【发布时间】:2010-02-05 12:11:39
【问题描述】:

我正在做一个项目,我需要为项目的一个阶段设计和使用一组类。

在随后的阶段,我们将不再需要这组类和方法。这些类和方法集将在整个应用程序中使用,因此如果我将它们作为任何其他类添加,我需要在不需要它们时手动删除它们。

C#中有没有办法,可以在类或者类实例化的地方设置一个属性,避免实例化和基于属性值的方法调用。

类似,设置

[Phase = 2]
BridgingComponent bridgeComponent = new BridgeComponent();

在这方面的任何帮助表示赞赏。

【问题讨论】:

  • 我想到了控制反转/依赖注入。

标签: c# class-design conditional-compilation


【解决方案1】:

当 C# 编译器遇到 #if directive,最后是 #endif 指令时,仅当定义了指定符号时,它才会编译指令之间的代码。

#define FLAG_1
...
#if FLAG_1
    [Phase = 2]
    BridgingComponent bridgeComponent = new BridgeComponent();
#else
    [Phase = 2]
    BridgingComponent bridgeComponent;
#endif

【讨论】:

  • 这个 DEBUG 可以是 App.config 中的值吗?
  • 您可以声明自己的预编译器变量,但不能动态声明。 #define MY_FLAG
【解决方案2】:

听起来你要的是#if

#if Phase2
BridgingComponent bridgeComponent = new BridgeComponent();
#endif

当你希望 BridgingComponent 包含在构建中时,然后在编译行上使用 /define Phase2,如果不包含则不要。

【讨论】:

  • 我认为#if 是我需要的。谢谢布莱尔
【解决方案3】:

在 Properties>build 中设置编译标志,例如第一阶段

在代码中

#if PHASE1
  public class xxxx
#endif

【讨论】:

    【解决方案4】:

    您还可以使用 Spring.NET、NInject 等依赖注入框架。另一种方法是使用工厂方法来实例化您的类。然后,您将拥有 Phase1、Phase2 等的工厂类。在后一种情况下,您可以选择运行时而不是编译时。

    【讨论】:

      【解决方案5】:

      关于方法,可以使用Conditional属性:

      // Comment this line to exclude method with Conditional attribute
      #define PHASE_1
      
      using System;
      using System.Diagnostics;
      class Program {
      
          [Conditional("PHASE_1")]
          public static void DoSomething(string s) {
              Console.WriteLine(s);
          }
      
          public static void Main() {
              DoSomething("Hello World");
          }
      }
      

      好在如果符号没有定义,方法调用就不会被编译。

      【讨论】:

      • 对于方法,我可以使用它。谢谢!
      猜你喜欢
      • 1970-01-01
      • 2013-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-19
      相关资源
      最近更新 更多