在 Mac OS 上設定 C#

Saad Aslam 2023年10月12日
  1. 在 Mac OS 上安裝和設定 C#
  2. 在 Mac OS 上使用 C# 啟動新專案
在 Mac OS 上設定 C#

本文將演示 Mac OS 上 C# 語言的完整設定和基本語法。

在 Mac OS 上安裝和設定 C#

以下是在 Mac 上安裝和設定 C# 的步驟。

  • 第一步是在你的計算機上安裝 IDE。Visual Studio Code 是最佳選擇,因為它具有你需要的所有功能並且非常易於使用。
  • 訪問 Visual Studio 網站。從四個選項中,選擇 Visual Studio Code 並單擊 Download for Mac 按鈕。
  • 解壓縮包並將 Visual Studio Code 拖到你的應用程式資料夾中。之後,你可以從同一資料夾訪問它。
  • 然後可以通過使用快捷鍵 Shift+Cmd+X</kbd 在 Visual Studio Code 中進入 Extensions 窗格來下載 C# 擴充套件> 或選擇程式碼 > 首選項 > 擴充套件
  • 在擴充套件顯示的搜尋欄中鍵入 C# 並找到 Microsoft 的。安裝 C# 擴充套件後,單擊安裝並重新啟動 Visual Studio Code。

在 Mac OS 上使用 C# 啟動新專案

在 Mac 上開啟 Applications > Utilities 中的終端以啟動你的第一個專案。例如,在終端上編寫 dotnet new console -o projectName 以構建控制檯應用程式。

然後,開啟 Visual Studio Code 並導航到你在終端中定義的資料夾。最後,從左側資源管理器中開啟 Program.cs 檔案開始程式設計。

C# 語法的最基本形式

在理解基礎知識方面,C# 是一種相對簡單的語言。它不像 Python 那樣容易學習,但也不像 C++ 那樣難。

我們將從最基本的程式設計任務開始:在螢幕上顯示文字並接受使用者輸入。

當你開啟 Program.cs 檔案時,你將獲得以下樣板程式碼:

using System;

namespace projectName {
  class Program {
    static void Main(string[] args) {
      Console.WriteLine("Hello World");
    }
  }
}

輸出:

Hello World

讓我們嘗試幾行程式碼,看看我們能想出什麼。

宣告一個字串資料型別的變數 data

string data;

我們需要顯示一條訊息來向使用者詢問一些事情。讓我們問他們的名字。

Console.WriteLine("What's your name?");

然後我們需要檢索使用者的輸入並將其儲存到我們定義的 data 變數中。為此,我們使用了一個名為 Console.ReadLine() 的函式,該函式接受使用者輸入。

data = Console.ReadLine();

之後,只需在螢幕上顯示我們收集的資訊即可。

Console.WriteLine("Hello " + data);

因為使用者名稱儲存在 data 變數中,所以該行將輸出帶有所提供名稱的靜態 Hello

完整程式碼:

using System;

namespace ProjectName {
  class Program {
    static void Main(string[] args) {
      string data;
      Console.WriteLine("What's your name?");
      data = Console.ReadLine();
      Console.WriteLine("Hello " + data);
    }
  }
}

輸出:

What's your name?
Henry
Hello Henry
作者: Saad Aslam
Saad Aslam avatar Saad Aslam avatar

I'm a Flutter application developer with 1 year of professional experience in the field. I've created applications for both, android and iOS using AWS and Firebase, as the backend. I've written articles relating to the theoretical and problem-solving aspects of C, C++, and C#. I'm currently enrolled in an undergraduate program for Information Technology.

LinkedIn