Fis*_*ish 3 .net c# asp.net cross-platform .net-standard-2.0
我知道有一种方法可以为目标框架有条件地编译,例如 #if net461 ....#elif .... 但是有没有一种方法可以为特定的 os 有条件地编译,例如 target _os_MAC 或 target_os_win
如果有人可以指导我如何实现它的文档或教程?
第 2 部分:另外,有没有办法创建自定义标签,这样每当新目标操作系统或框架发生更改时,我就不必更改每个标签。例如,从 net461 到 net471
这是一个老问题,但如果现在有人来这里,还有更好的选择。
您不需要有不同的配置并手动选择要使用的配置。
您可以使用 System.Runtime.InteropServices.RuntimeInformation。 https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.runtimeinformation?view=netframework-4.8
这里有一个很好的手册:https ://blog.magnusmontin.net/2018/11/05/platform-conditional-compilation-in-net-core/ 链接中的最少信息:更改您的 .csproj 文件
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
<IsWindows Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Windows)))' == 'true'">true</IsWindows>
<IsLinux Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Linux)))' == 'true'">true</IsLinux>
</PropertyGroup>
<PropertyGroup Condition="'$(IsWindows)'=='true'">
<DefineConstants>Windows</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(IsLinux)'=='true'">
<DefineConstants>Linux</DefineConstants>
</PropertyGroup>
Run Code Online (Sandbox Code Playgroud)
这将有条件地定义常量。你以后会像这样使用:
#if Linux
Console.WriteLine("Built on Linux!");
#elif Windows
Console.WriteLine("Built in Windows!");
#endif
Run Code Online (Sandbox Code Playgroud)
这个答案假设您正在询问自定义预处理器符号(这就是我的解释方式 - 如果我错了,请纠正我。
您可以使用自定义构建配置:
首先进入构建配置管理器..
接下来,创建一个新的构建配置。您可以从现有配置复制配置:
然后,右键单击您的项目并转到“属性”。在构建选项卡下,定义条件编译符号:
对 Windows 执行同样的操作。
然后你可以编写如下的条件步骤:
class Program
{
static void Main(string[] args)
{
#if MACOS
Console.WriteLine("OSX");
#elif WINDOWS
Console.WriteLine("Windows");
#endif
Console.Read();
}
Run Code Online (Sandbox Code Playgroud)
根据您选择的构建配置..您将获得: