Visual Studio Code 成為個人使用頻率最高的應用程式了,層出不窮的插件為 Code 的應用場景提供了無限可能。本文介紹在 Visual Studio Code 中開發 .NET 程式的方法。
Prerequisite
- 安裝 .Net Core SDK
- 在 Visual Studio Code 中安裝 C# 擴充, 安裝後重新開機 Visual Studio Code 即可使用。
使用 Visual Studio 開發 .NET Core程式
建立一個名為 csharp-workspace 的檔案夾,選中檔案夾,右鍵選擇通過Code打開,進入 Visual Studio Code。通過快捷鍵 Ctrl + ` 打開 Terminal 視窗。
在 Termnial 視窗輸入下面的指令,建立 console 類型項目:
使用 dotnet 指令建立的 hellocsharp 檔案夾,c# 開發依賴 OmniSharp,OmniSharp 自動下載下傳。如果插件安裝沒有問題,Visual Studio Code 提示選擇 Project,選擇其中任意一項都行。
然後 C# 擴充在右下角彈出如下提示:
點選 Yes,在 .code 檔案夾下面建立 launch.json 檔案和 tasks.json 檔案。然後在 Terminal 中輸入
dotnet run
指令即可運作。
vscode-solution-explorer 插件
vscode-solution-explorer 插件提供類似 Visual Studio IDE 對解決方案和 Project 管理,不用去記 dotnet 指令。
安裝完成後,在左邊的面闆中多了一個圖示:
點選該圖示,進入 Solution Explore 界面。因為目前還沒有建立 Solution ,是以頁面為空。Ctrl + Shift + P 快捷鍵打開 Visual Studio Code 的指令面闆 (Command Palette),找到 Create new empty solution 指令:
将要建立的 solution 命名為 hellosolution,建立完成後,右鍵選中 hellosolution,可以建立 Project 或者添加已有的 Project。vscode-solution-explorer 支援多種項目類型,非常友善。
我們使用剛建立的 hellocsharp 項目。完成後左邊 Solution Explorer 界面如下:
選中 hellosolution,右鍵,可以選中如下的指令,比如 build, clean 等:
選中 hellocsharp 項目,右鍵可以選擇 Run 指令來運作項目。
調試
Visual Studio Code 也支援 .NET 程式的調試。為了測試調試,我将程式稍作變更,添加兩個變量:
namespace hellocsharp
{
class Program
{
static void Main(string[] args)
{
int a = 1;
int b = 2;
Console.WriteLine($"Hello World! {a + b} ");
}
}
}
設定一個斷點,然後按下 F5 調試程式:
完美。