Alternatives to Conditional Compilation in C#

前端 未结 7 2454
感情败类
感情败类 2021-02-07 21:17

What is the alternative to having code with conditional compilation in C#?

I have a class that has lots of code that is based on # ifdef .. After sometime my code is unr

7条回答
  •  星月不相逢
    2021-02-07 21:40

    If it's a code-readability issue, you might consider using .Net's partial class qualifier and put the conditional code in separate files, so maybe you could have something like this...

    foo.cs:

    public partial class Foo
    {
        // Shared Behavior
    }
    

    foo.Debug.cs:

    #if DEBUG
    public partial class Foo
    {
        // debug Behavior
    }
    #endif
    

    foo.bar.cs:

    #define BAR
    #if BAR
    public partial class Foo
    {
        // special "BAR" Behavior
    }
    #endif
    

    I'm not sure whether or not you can define your conditionals outside of the code file though, so doing something like this might reduce the flexibility of the conditional definitions (e.g. you might not be able to create a conditional branch against BAR in, say, the main file, and having to maintain multiple defined BARs could get ugly) as well as require a certain dilligence to go to the files to effectively enable/disable that bit of code.

    So, using this approach might end up introducing more complications than it solves, but, depending on your code, maybe it could be helpful?

提交回复
热议问题