如何在 Visual Studio 加上自訂 Build Type

Ryan Hsu
Ryan Hsu
Aug 29, 2017 · 4 min read

需求

在 csproj 檔案 import 自訂的 build type,讓我們可以在 code 理面做 build type 的判斷!

為什麼不用 Visual Studio 的 GUI 做?

因為會把所有 website 包含 library 都加上這個設定,但我們並不一定需要這樣做,而且一但要改全部的 csproj 都要改,會變得很麻煩!我們要把改變封裝起來!

步驟

加上自定義 build type 的設定檔(xml),這邊我們把自訂的 build type 叫做 CUSTOM

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Choose>
<When Condition=" '$(Configuration)|$(Platform)' == 'CUSTOM|AnyCPU' ">
<PropertyGroup>
<Optimize>true</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>CUSTOM</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
</When>
</Choose>
</Project>

並且在 csproj 檔案裡面 import 這個設定檔!

如果不知道怎麼 import 自訂選項請看:C# 如何在 MsBuild 加上自訂選項或流程

我已經 import 了,但為什麼 Visual Studio 還看不到新的 build type?

在 solution 檔案裡,要再 GlobalSection 區域中加上新的 build type

GlobalSection(SolutionConfigurationPlatforms) = preSolution
CUSTOM|Any CPU = CUSTOM|Any CPU
CUSTOM|x86 = CUSTOM|x86
EndGlobalSection

然後開啟 solution 檔案並用 Visual Studio 跑一次 Rebuild,成功後存檔關掉即可!

這麼做的用意是,讓 solution 檔案自動產生每個 project (在 solution 檔案裡面是對應各個 project 的 GUID) 對應的 GlobalSection 設定!

如何在 C# code 裡面判斷自定義的 build type?

語法是:

#if CUSTOM
#endif
//或是#if !CUSTOM
#endif

CUSTOM 的判斷到底要大寫還是小寫?

這個跟著你自訂的 build type 設定檔 (xml) 有關,裡面有一個 DefineConstants 就是定義你到底要用來判斷的文字囉!

其實你可以把一段程式碼用不等於 build type 判斷包起來,並且選擇目標的 build type,你會發現 Visial Studio 把裡面的程式碼變成灰色的區域!這樣就代表你成功囉!(我使用的版本是 Visual Studio 2017 professional)

總結一下這樣做的優點

自訂 build type 可以讓你的程式碼在某些情況不跑某些 code,在對於某些開發情況下其實是很有利的,又或是說你可能需要起網站,但又只要使用網站部分功能,那麼也能透過這個方式來節省時間!

以上

記錄一下,希望對你也有幫助!

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade