Conditional compilation based on constants?

前端 未结 1 1863
面向向阳花
面向向阳花 2021-01-25 09:54

Is it possible to conditionally compile classes and methods based on some constant value defined in a class, for example I\'d like to have something like that.

p         


        
1条回答
  •  生来不讨喜
    2021-01-25 10:27

    No -

    C# does not evaluate expressions in the #if preprocessor directive - it only looks to see if the symbol is defined :

    When the C# compiler encounters an #if directive, followed eventually by an #endif directive, it compiles the code between the directives only if the specified symbol is defined. Unlike C and C++, you cannot assign a numeric value to a symbol. The #if statement in C# is Boolean and only tests whether the symbol has been defined or not.

    (emphasis added)

    So the proper way to do what you want is to do:

    public class SomeClass {
       #if BUILD_MODE_ONE
           public void SomeMethod() { /* Implementation one */ }
       #elif BUILD_MODE_TWO
           public void SomeMethod() { /* Implementation two */ }
       #elif BUILD_MODE_THREE
           public void SomeMethod() { /* Implementation three */ }
       #endif
    }
    

    Where the symbol could either be defined in that code file or via command-line parameters to CSC.EXE.

    0 讨论(0)
提交回复
热议问题