C# 条件编译-C语言中代码的逐步淘汰部分#

C# 条件编译-C语言中代码的逐步淘汰部分#,c#,class-design,conditional-compilation,C#,Class Design,Conditional Compilation,我正在做一个项目,我需要为项目的一个阶段设计和使用一组类 在随后的阶段中,我们将不需要类和方法集。这些类和方法集将在整个应用程序中使用,因此,如果我将它们作为任何其他类添加,我将需要在不需要它们时手动删除它们 在C#中是否有一种方法,可以在类或类实例化的位置上设置属性,以避免基于属性值的实例化和方法调用 比如说,布景 [Phase = 2] BridgingComponent bridgeComponent = new BridgeComponent(); 这方面的任何帮助都值得赞赏。当C#编

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

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

在C#中是否有一种方法,可以在类或类实例化的位置上设置属性,以避免基于属性值的实例化和方法调用

比如说,布景

[Phase = 2]
BridgingComponent bridgeComponent = new BridgeComponent();
这方面的任何帮助都值得赞赏。

当C#编译器遇到一个#endif指令,然后是一个#endif指令时,它将仅在定义了指定符号的情况下在指令之间编译代码

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

听起来像是你要的


然后在编译行中使用
/define Phase2
,当您希望BridgingComponent包含在生成中时,不要使用。在属性>生成中设置编译标志,例如PHASE1

在代码中

#if PHASE1
  public class xxxx
#endif

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

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

// 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");
    }
}

好的是,如果没有定义符号,则不会编译方法调用。

此调试是否类似于App.config中的值?您可以声明自己的预编译器变量,但不能动态地声明afak<代码>#定义我的#标志我想到了控制反转/依赖注入。我想#如果是我需要的。谢谢Blair的方法,我可以用这个。谢谢
// 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");
    }
}