C# preprocessor differentiate between operating systems

久未见 提交于 2020-05-23 02:52:53

问题


Is it possible to differentiate between operating systems in C# using preprocessor? like :

#if OS_WINDOWS
//windows methods
#elif OS_MAC
//mac  methods
#elif OS_LINUX
//linux methods
#endif

回答1:


What you are asking for is possible but needs a bit of work.

  1. Define a preprocessor variable in your csproj

    <PropertyGroup Condition=" '$(OS)' == 'Windows_NT' ">
      <DefineConstants>_WINDOWS</DefineConstants>
    </PropertyGroup>
    
  2. Use that in your code

    #if _WINDOWS
      // your windows stuff
    #else
      // your *nix stuff
    #endif
    

I find this technique useful when you have constants that are dependent on the OS (for example native library names)




回答2:


No. Sadly you can't. And it is even logical: if you compile for AnyCPU, then your program is executable on any platform.

What you can do is create multiple project configurations, where you set the #define you want (in the Properties of the project, Build, Conditional compilation symbols).

But perhaps this is a XY problem... Normally you don't need to do it, and you can live with a

if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{

}
else if (Environment.OSVersion.Platform == PlatformID.MacOSX)
{

}
else if (Environment.OSVersion.Platform == PlatformID.Unix)
{

}



回答3:


No - think about it, the compiler runs once, but the same binary output can be used on multiple machines.

Now you can specify any symbols you want when you compile - so you could easily compile three different times and pass in different preprocessor symbols each time.

If you don't need any compile-time changes, you can just use Environment.OSVersion to detect the operating system you're running under.



来源:https://stackoverflow.com/questions/30153797/c-sharp-preprocessor-differentiate-between-operating-systems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!