簡體   English   中英

os的Visual Studio條件編譯

[英]Visual studio conditional compilation for os

我知道有一種方法可以為目標框架有條件地編譯,例如 #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>

這將有條件地定義常量。 你以后會像這樣使用:

#if Linux
    Console.WriteLine("Built on Linux!"); 
#elif Windows
    Console.WriteLine("Built in Windows!"); 
#endif

這個答案假設您在詢問自定義預處理器符號(這就是我的解釋方式 - 如果我錯了,請糾正我。

您可以使用自定義構建配置:

首先進入構建配置管理器..

配置管理器

接下來,創建一個新的構建配置。 您可以從現有配置復制配置:

創建新配置

然后,右鍵單擊您的項目並轉到屬性。 在 build 選項卡下,定義一個條件編譯符號:

條件編譯符號

對 Windows 執行相同操作。

然后您可以編寫如下條件步驟:

    class Program
{
    static void Main(string[] args)
    {
#if MACOS
        Console.WriteLine("OSX");
#elif WINDOWS
        Console.WriteLine("Windows");
#endif

        Console.Read();
    }

根據您選擇的構建配置..您將獲得:

操作系統:

操作系統

窗戶:

窗戶

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM