Compiler #if directive to split between Mono and .

2019-02-06 10:02发布

问题:

This question already has an answer here:

  • How can I conditionally compile my C# for Mono vs. Microsoft .NET? 2 answers

I need to dual-compile a class library for Mono on the Mac and .NET on the PC. There are some minor changes I want to make, but I was hoping to split the code using a compiler directive. Any suggestions?

回答1:

Well you could certainly use

#if MONO

and then compile with

gmcs -define:MONO ...

(Or put it in your Mono build configuration, of course. It really depends on how you're building your library.)

... what are you looking for beyond that?



回答2:

While a runtime check is probably preferable, with the Mono compiler, the pre-defined __MonoCS__ constant is useful, e.g.:

#if __MonoCS__
// Code for Mono C# compiler.
#else
// Code for Microsoft C# compiler.
#endif


回答3:

Preferred way is to use runtime detection, as this allows for the same assemblies to be used on either platform:

using System;

class Program {
    static void Main ()
    {
        Type t = Type.GetType ("Mono.Runtime");
        if (t != null)
             Console.WriteLine ("You are running with the Mono VM");
        else
             Console.WriteLine ("You are running something else");
    }
}


标签: c# .net mono