Conditional Compilation - Phasing out a piece of code in C #

I am working on a project where I need a set of classes that will be developed and used for one phase of the project.

In the next step, we do not need a set of classes and methods. This set of classes and methods will be used throughout the application, so if I add them like any other classes, I will need to manually remove them if they are not required.

Is there a way in C # so that I can set the attribute of the class or the places where the class is instantiated to avoid calling the instance and method based on the attribute value.

Something like installation

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

Any help was appreciated on this front.

+4
source share
5 answers

Looks like you're asking for # if .

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

And then use /define Phase2 in the compilation line when you want the BridgingComponent to be included in the assembly, and don't do it when you don't.

+2
source

When the C # compiler encounters # if directive , the #endif directive ultimately follows, it will only compile code between directives if the specified character is defined.

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

Set the compilation flag in properties> assembly, for example. PHASE1

and in code

 #if PHASE1 public class xxxx #endif 
+1
source

You can also use the dependency injection framework like Spring.NET, NInject, etc. Another way is to use factory methods to instantiate your classes. Then you will have a factory class for Phase1, for Phase2, etc. In the latter case, instead of compiling time, you choose the runtime.

+1
source

About the methods you can use the Conditional attribute:

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

It is good that if the character is not defined, method calls are not compiled.

+1
source

Source: https://habr.com/ru/post/1300412/


All Articles