隔离单一特定代码

时间:2011-03-01 20:01:01

标签: c# mono

我正在玩Gtk#GUI到Windows.Forms应用程序。我需要一种方法来隔离Program.cs中的特定于Mono的代码,因为我想避免创建单独的.sln / .csproj。在C / C ++ / Objective-C项目中,我会执行与#ifdef __APPLE__#ifdef _WIN32类似的操作。

C#似乎有#if命令。

隔离Mono特定代码或Visual Studio特定代码的典型方法是什么?

1 个答案:

答案 0 :(得分:35)

您可以使用#define定义符号,并使用#if#else进行检查。

您还可以使用/define编译器选项将符号传递给编译器。

请参阅C#预处理程序指令的完整列表here

#define MONO // Or pass in "/define MONO" to csc 

#if MONO
 //mono specific code
#else 
 //other code
#endif

根据this SO回答,单声道编译器定义了一个__MonoCS__符号,因此以下内容可行:

#if __MonoCS__
 //mono specific code
#else 
 //other code
#endif

this answer @Mystic详述的单声道“移植到Windows”指南的推荐方法是:

public static bool IsRunningOnMono ()
{
    return Type.GetType ("Mono.Runtime") != null;
}

当然,这是运行时检查,而不是上面的编译时间检查,因此可能不适用于您的特定情况。