教學課程:在 Visual Studio 中建立簡單的 C# 主控台應用程式 (第 1 部分,)
適用于:Visual Studio
Visual Studio for Mac
Visual Studio Code
在本教學課程中,您會使用 Visual Studio 來建立和執行 C# 主控台應用程式,並探索 Visual Studio 整合式開發環境的某些功能, (IDE) 。 本教學課程是兩部分教學課程系列的第 1 部分。
在本教學課程中,您:
- 建立 Visual Studio 專案。
- 建立 C# 主控台應用程式。
- 對您的應用程式進行偵錯。
- 關閉您的應用程式。
- 檢查完整的程式碼。
在第 2 部分中,您會擴充此應用程式以新增更多專案、瞭解偵錯技巧,以及參考協力廠商套件。
必要條件
您必須安裝 Visual Studio。
如果您尚未安裝 Visual Studio,請前往 Visual Studio 下載頁面免費進行安裝。
建立專案
若要開始,請建立 C# 應用程式專案。 專案類型隨附您需要的所有範本檔案。
開啟 Visual Studio,然後選擇 [開始] 視窗中 的 [建立新專案 ]。
在 [ 建立新專案 ] 視窗中,從 [語言] 清單中選擇 [C# ]。 接下來,從 [平臺] 清單選擇 [Windows ],並從專案類型清單中選擇 [主控台 ]。
套用語言、平臺和專案類型篩選之後,請選擇 [主控台應用程式 ] 範本,然後選取 [ 下一步]。
注意
如果您沒有看到 主控台應用程式 範本,請選取 [安裝更多工具和功能]。
接下來,在 Visual Studio 安裝程式中選擇 .NET Core 跨平台開發工作負載。
接下來,選擇 Visual Studio 安裝程式中的 [修改] 按鈕。 系統可能會提示您儲存工作,若收到提示,請依提示執行。 接下來,選擇 [繼續] 以安裝工作負載。 然後,返回至「建立專案」程序中的步驟 2。
在 [設定您的新專案] 視窗的 [專案名稱] 方塊中鍵入或輸入 Calculator。 然後選擇 [ 下一步]。
在 [ 其他資訊 ] 視窗中,應該已為您的目標 Framework 選取 .NET Core 3.1 。 如果沒有,請選取 [.NET Core 3.1]。 然後選擇 [ 建立]。
Visual Studio 會隨即開啟您的新專案,其中包含預設 "Hello World" 程式碼。 若要在編輯器中檢視它,請在 [方案總管] 視窗中選取程式碼檔案Program.cs,這通常是在 Visual Studio 右側。
預設的 「Hello World」 程式碼會呼叫 WriteLine 方法,在主控台視窗中顯示常值字串 「Hello, World!」 。 如果您按下 F5,您可以在 [偵錯] 模式中執行預設程式。 在偵錯工具中執行應用程式之後,主控台視窗會保持開啟狀態。 按任意鍵關閉主控台視窗。
開啟 Visual Studio,然後選擇 [開始] 視窗中 的 [建立新專案 ]。
在 [ 建立新專案 ] 視窗中,選取 [ 所有語言],然後從下拉式清單中選擇 [C# ]。 從 [所有平臺] 清單中選擇[Windows],然後從 [所有專案類型] 清單中選擇[主控台]。
套用語言、平臺和專案類型篩選之後,請選擇 主控台應用程式 範本,然後選取 [ 下一步]。
注意
如果您沒有看到 主控台應用程式 範本,請選取 [安裝更多工具和功能]。
在Visual Studio 安裝程式中,選擇.NET 桌面開發工作負載,然後選取 [修改]。
在 [設定新專案] 視窗中,在 [專案名稱] 方塊中輸入或輸入Calculator,然後選取 [下一步]。
在 [ 其他資訊 ] 視窗中,選取目標 Framework 的 .NET 7.0 ,然後選取 [ 建立]。
Visual Studio 會隨即開啟您的新專案,其中包含預設 "Hello World" 程式碼。
若要在編輯器中檢視它,請在 [方案總管] 視窗中選取程式碼檔案Program.cs,這通常是在 Visual Studio 右側。
單一程式碼語句會 WriteLine 呼叫 方法,在主控台視窗中顯示常值字串 「Hello, World!」 。 如果您按下 F5,您可以在 [偵錯] 模式中執行預設程式。 在偵錯工具中執行應用程式之後,主控台視窗會保持開啟狀態。 按任意鍵關閉主控台視窗。
注意
從 .NET 6 開始,使用主控台範本的新專案會產生與舊版不同的程式碼。 若要深入瞭解,請參閱 新的 C# 範本產生最上層語句 頁面。
建立應用程式
在本節中,您可:
- 探索 C# 中的一些基本整數數學。
- 新增程式碼以建立基本計算機應用程式。
- 偵錯應用程式以尋找並修正錯誤。
- 精簡程式碼使其更有效率。
探索整數運算
從 C# 中的一些基本整數數學開始。
在程式碼編輯器中,刪除預設 "Hello World" 程式碼。
具體來說,刪除
Console.WriteLine("Hello World!");
一行。鍵入下列程式碼來取代:
int a = 42; int b = 119; int c = a + b; Console.WriteLine(c); Console.ReadKey();
請注意,當您這麼做時,Visual Studio 中的 IntelliSense 功能會提供您自動完成項目的選項。
選擇[計算機] 旁的綠色 [開始]按鈕來建置和執行程式,或按F5。
主控台視窗會隨即開啟並顯示 42 + 119 的總和,也就是 161。
(選擇性),您可以變更運算子來變更結果。 例如,您可以將
int c = a + b;
程式碼行中的+
運算子變更為-
進行相減、變更為*
進行相乘,或變更為/
進行相除。 在您執行程式時,結果也會變更。關閉主控台視窗。
在方案總管右窗格中,選取Program.cs以在程式碼編輯器中顯示檔案
在程式碼編輯器中,取代顯示
Console.WriteLine("Hello World!");
的預設 「Hello World」 程式碼。將 行取代為下列程式碼:
int a = 42; int b = 119; int c = a + b; Console.WriteLine(c); Console.ReadKey();
如果您輸入程式碼,Visual Studio IntelliSense 功能會提供自動完成專案的選項。
若要建置並執行您的應用程式,請按 F5鍵,或選取頂端工具列中名稱 [計算機 ] 旁的綠色箭號。
主控台視窗隨即開啟,顯示 42 + 119 的總和,也就是 161。
關閉主控台視窗。
您可以選擇性地變更 運算子來變更結果。 例如,您可以將
int c = a + b;
程式碼行中的+
運算子變更為-
進行相減、變更為*
進行相乘,或變更為/
進行相除。 當您執行應用程式時,結果會隨之變更。
新增程式碼來建立計算機
繼續將更複雜的計算機程式碼集新增至您的專案。
在程式碼編輯器中,以下列新程式碼取代 Program.cs 中的所有程式碼:
using System; namespace Calculator { class Program { static void Main(string[] args) { // Declare variables and then initialize to zero. int num1 = 0; int num2 = 0; // Display title as the C# console calculator app. Console.WriteLine("Console Calculator in C#\r"); Console.WriteLine("------------------------\n"); // Ask the user to type the first number. Console.WriteLine("Type a number, and then press Enter"); num1 = Convert.ToInt32(Console.ReadLine()); // Ask the user to type the second number. Console.WriteLine("Type another number, and then press Enter"); num2 = Convert.ToInt32(Console.ReadLine()); // Ask the user to choose an option. Console.WriteLine("Choose an option from the following list:"); Console.WriteLine("\ta - Add"); Console.WriteLine("\ts - Subtract"); Console.WriteLine("\tm - Multiply"); Console.WriteLine("\td - Divide"); Console.Write("Your option? "); // Use a switch statement to do the math. switch (Console.ReadLine()) { case "a": Console.WriteLine($"Your result: {num1} + {num2} = " + (num1 + num2)); break; case "s": Console.WriteLine($"Your result: {num1} - {num2} = " + (num1 - num2)); break; case "m": Console.WriteLine($"Your result: {num1} * {num2} = " + (num1 * num2)); break; case "d": Console.WriteLine($"Your result: {num1} / {num2} = " + (num1 / num2)); break; } // Wait for the user to respond before closing. Console.Write("Press any key to close the Calculator console app..."); Console.ReadKey(); } } }
選取 [計算機] 按鈕或按 F5 來執行您的應用程式。
主控台視窗隨即開啟。
在主控台視窗中,遵循提示將數位 42 和 119 加在一起。
您的應用程式看起來應該類似下列螢幕擷取畫面:
在程式碼編輯器中,以下列新程式碼取代 Program.cs 中的所有程式碼:
// Declare variables and then initialize to zero. int num1 = 0; int num2 = 0; // Display title as the C# console calculator app. Console.WriteLine("Console Calculator in C#\r"); Console.WriteLine("------------------------\n"); // Ask the user to type the first number. Console.WriteLine("Type a number, and then press Enter"); num1 = Convert.ToInt32(Console.ReadLine()); // Ask the user to type the second number. Console.WriteLine("Type another number, and then press Enter"); num2 = Convert.ToInt32(Console.ReadLine()); // Ask the user to choose an option. Console.WriteLine("Choose an option from the following list:"); Console.WriteLine("\ta - Add"); Console.WriteLine("\ts - Subtract"); Console.WriteLine("\tm - Multiply"); Console.WriteLine("\td - Divide"); Console.Write("Your option? "); // Use a switch statement to do the math. switch (Console.ReadLine()) { case "a": Console.WriteLine($"Your result: {num1} + {num2} = " + (num1 + num2)); break; case "s": Console.WriteLine($"Your result: {num1} - {num2} = " + (num1 - num2)); break; case "m": Console.WriteLine($"Your result: {num1} * {num2} = " + (num1 * num2)); break; case "d": Console.WriteLine($"Your result: {num1} / {num2} = " + (num1 / num2)); break; } // Wait for the user to respond before closing. Console.Write("Press any key to close the Calculator console app..."); Console.ReadKey();
選取 [計算機] 按鈕或按 F5 來執行您的應用程式。
主控台視窗隨即開啟。
在主控台視窗中,遵循提示將數位 42 和 119 加在一起。
您的應用程式看起來應該類似下列螢幕擷取畫面:
新增十進位功能
現在,調整程式碼以新增更多功能。
目前的計算機應用程式只接受並傳回整數。 例如,如果您執行應用程式,並將數位 42 除以數位 119,則結果為零,這不是確切的結果。
若要修正程式碼,藉由處理小數點來改善精確度:
從 Visual Studio 編輯器中的Program.cs,按Ctrl+H開啟[尋找和取代] 控制項。
在 控制項中輸入int,然後在[取代] 欄位中輸入float。
選取 [比對大小寫]和 [比對控制項中的整字] 圖示,或按Alt+C和Alt+W。
選取[全部取代] 圖示,或按Alt+A來執行搜尋並取代。
再次執行計算機應用程式,並將數位 42 除以數位 119。
應用程式現在會傳回十進位數,而不是零。
現在應用程式可以產生小數結果。 對程式碼進行更多調整,讓應用程式也可以計算小數點。
使用 Find 和 Replace 控制項將變數的每個實例
float
變更為double
,並將 方法的每個實例Convert.ToInt32
變更為Convert.ToDouble
。執行計算機應用程式,並將數位 42.5 除以數位 119.75。
應用程式現在接受十進位值,並傳回較長的小數數位作為結果。
在 [修改程式碼] 區段中,您可以減少結果中的小數位數。
偵錯應用程式
您已改善基本計算機應用程式,但您的應用程式尚未處理例外狀況,例如使用者輸入錯誤。 例如,如果使用者嘗試除以零或輸入非預期的字元,應用程式可能會停止運作、傳回錯誤,或傳回非數值的非數值結果。
讓我們逐步解說一些常見的使用者輸入錯誤,並在偵錯工具中找到它們,並在程式碼中加以修正。
提示
如需偵錯工具及其運作方式的詳細資訊,請參閱Visual Studio 偵錯工具。
修正「除以零」錯誤
如果您嘗試將數位除以零,主控台應用程式可能會凍結,然後在程式碼編輯器中顯示錯誤。
注意
有時候應用程式不會凍結,而且偵錯工具不會顯示零除錯誤。 相反地,應用程式可能會傳回非數值結果,例如無限大符號。 下列程式碼修正仍適用。
若要變更程式碼以處理此錯誤:
在 Program.cs中,將 的程式
case "d":
代碼取代為 下列程式碼:// Ask the user to enter a non-zero divisor until they do so. while (num2 == 0) { Console.WriteLine("Enter a non-zero divisor: "); num2 = Convert.ToInt32(Console.ReadLine()); } Console.WriteLine($"Your result: {num1} / {num2} = " + (num1 / num2)); break; }
取代程式碼之後,區段
switch
應該看起來類似下列螢幕擷取畫面:
現在,當您將任何數位除以零時,應用程式會要求另一個數位,並持續詢問直到您提供非零的數位為止。
修正「格式」錯誤
如果您在應用程式需要數值字元時輸入字母字元,則應用程式會凍結。 Visual Studio 會在程式碼編輯器中顯示錯誤。
若要避免此例外狀況,您可以重構先前輸入的程式碼。
修改程式碼
您不必依賴 program
類別來處理所有程式碼,而是可以將您的應用程式分割成兩個類別: Calculator
和 Program
。
類別 Calculator
會處理大量計算工作,而 類別會 Program
處理使用者介面和錯誤處理工作。
讓我們開始吧。
在 Program.cs中,刪除所有專案並新增下列新
Calculator
類別:class Calculator { public static double DoOperation(double num1, double num2, string op) { double result = double.NaN; // Default value is "not-a-number" if an operation, such as division, could result in an error. // Use a switch statement to do the math. switch (op) { case "a": result = num1 + num2; break; case "s": result = num1 - num2; break; case "m": result = num1 * num2; break; case "d": // Ask the user to enter a non-zero divisor. if (num2 != 0) { result = num1 / num2; } break; // Return text for an incorrect option entry. default: break; } return result; } }
另新增類別
Program
,如下所示:class Program { static void Main(string[] args) { bool endApp = false; // Display title as the C# console calculator app. Console.WriteLine("Console Calculator in C#\r"); Console.WriteLine("------------------------\n"); while (!endApp) { // Declare variables and set to empty. string numInput1 = ""; string numInput2 = ""; double result = 0; // Ask the user to type the first number. Console.Write("Type a number, and then press Enter: "); numInput1 = Console.ReadLine(); double cleanNum1 = 0; while (!double.TryParse(numInput1, out cleanNum1)) { Console.Write("This is not valid input. Please enter an integer value: "); numInput1 = Console.ReadLine(); } // Ask the user to type the second number. Console.Write("Type another number, and then press Enter: "); numInput2 = Console.ReadLine(); double cleanNum2 = 0; while (!double.TryParse(numInput2, out cleanNum2)) { Console.Write("This is not valid input. Please enter an integer value: "); numInput2 = Console.ReadLine(); } // Ask the user to choose an operator. Console.WriteLine("Choose an operator from the following list:"); Console.WriteLine("\ta - Add"); Console.WriteLine("\ts - Subtract"); Console.WriteLine("\tm - Multiply"); Console.WriteLine("\td - Divide"); Console.Write("Your option? "); string op = Console.ReadLine(); try { result = Calculator.DoOperation(cleanNum1, cleanNum2, op); if (double.IsNaN(result)) { Console.WriteLine("This operation will result in a mathematical error.\n"); } else Console.WriteLine("Your result: {0:0.##}\n", result); } catch (Exception e) { Console.WriteLine("Oh no! An exception occurred trying to do the math.\n - Details: " + e.Message); } Console.WriteLine("------------------------\n"); // Wait for the user to respond before closing. Console.Write("Press 'n' and Enter to close the app, or press any other key and Enter to continue: "); if (Console.ReadLine() == "n") endApp = true; Console.WriteLine("\n"); // Friendly linespacing. } return; } }
選取 [計算機] 按鈕或按 F5 來執行您的應用程式。
遵循提示,將數字 42 除以數字 119。 您的結果看起來應該類似下列螢幕擷取畫面:
您現在可以執行更多計算,直到您選擇關閉主控台應用程式為止。 結果中也有較少的小數位數。 如果您輸入不正確的字元,您會收到適當的錯誤回應。
關閉應用程式
如果您尚未這麼做,請關閉計算機應用程式。
關閉 Visual Studio 中的 [ 輸出] 窗格。
在 Visual Studio 中,按Ctrl+S以儲存您的應用程式。
新增 Git 原始檔控制
既然您已建立應用程式,您可能想要將其新增至 Git 存放庫。 Visual Studio 可讓您直接從 IDE 使用 Git 工具,輕鬆處理該程式。
提示
Git 是最廣泛使用的新式版本控制系統,因此無論您是專業開發人員,還是學習程式碼,Git 都可以非常有用。 如果您不熟悉 Git,網站 https://git-scm.com/ 是很好的起點。 您可以在該處找到速查表、熱門的線上書籍和 Git 基本概念影片。
若要建立程式碼與 Git 的關聯,請先建立程式碼所在的新 Git 存放庫:
在 Visual Studio 右下角的狀態列中,選取 [ 新增至原始檔控制],然後選取 [Git]。
在 [ 建立 Git 存放庫 ] 對話方塊中,登入 GitHub。
存放庫名稱會根據您的資料夾位置自動填入。 您的新存放庫預設為私人存放庫,這表示您是唯一可以存取它的人員。
提示
不論您的存放庫是公用還是私人,最好是讓程式碼的遠端備份安全地儲存在 GitHub 上。 即使您未與小組合作,遠端存放庫仍可讓您從任何電腦使用您的程式碼。
選取 [建立並推送]。
建立存放庫之後,您會在狀態列中看到狀態詳細資料。
具有箭號的第一個圖示會顯示您最新分支中的傳出/傳入認可數目。 您可以使用此圖示來提取任何傳入認可,或推送任何傳出認可。 您也可以選擇先檢視這些認可。 若要這樣做,請選取圖示,然後選取 [ 檢視傳出/傳入]。
第二個具有鉛筆的圖示會顯示程式碼未認可的變更數目。 您可以選取此圖示,在 [Git 變更 ] 視窗中檢視這些變更。
若要深入瞭解如何搭配您的應用程式使用 Git,請參閱 Visual Studio 版本控制檔。
檢閱:程式碼完成
在本教學課程中,您已對計算機應用程式進行許多變更。 應用程式現在會更有效率地處理運算資源,並處理大部分的使用者輸入錯誤。
以下是完整程式碼總整理:
class Calculator
{
public static double DoOperation(double num1, double num2, string op)
{
double result = double.NaN; // Default value is "not-a-number" which we use if an operation, such as division, could result in an error.
// Use a switch statement to do the math.
switch (op)
{
case "a":
result = num1 + num2;
break;
case "s":
result = num1 - num2;
break;
case "m":
result = num1 * num2;
break;
case "d":
// Ask the user to enter a non-zero divisor.
if (num2 != 0)
{
result = num1 / num2;
}
break;
// Return text for an incorrect option entry.
default:
break;
}
return result;
}
}
class Program
{
static void Main(string[] args)
{
bool endApp = false;
// Display title as the C# console calculator app.
Console.WriteLine("Console Calculator in C#\r");
Console.WriteLine("------------------------\n");
while (!endApp)
{
// Declare variables and set to empty.
string numInput1 = "";
string numInput2 = "";
double result = 0;
// Ask the user to type the first number.
Console.Write("Type a number, and then press Enter: ");
numInput1 = Console.ReadLine();
double cleanNum1 = 0;
while (!double.TryParse(numInput1, out cleanNum1))
{
Console.Write("This is not valid input. Please enter an integer value: ");
numInput1 = Console.ReadLine();
}
// Ask the user to type the second number.
Console.Write("Type another number, and then press Enter: ");
numInput2 = Console.ReadLine();
double cleanNum2 = 0;
while (!double.TryParse(numInput2, out cleanNum2))
{
Console.Write("This is not valid input. Please enter an integer value: ");
numInput2 = Console.ReadLine();
}
// Ask the user to choose an operator.
Console.WriteLine("Choose an operator from the following list:");
Console.WriteLine("\ta - Add");
Console.WriteLine("\ts - Subtract");
Console.WriteLine("\tm - Multiply");
Console.WriteLine("\td - Divide");
Console.Write("Your option? ");
string op = Console.ReadLine();
try
{
result = Calculator.DoOperation(cleanNum1, cleanNum2, op);
if (double.IsNaN(result))
{
Console.WriteLine("This operation will result in a mathematical error.\n");
}
else Console.WriteLine("Your result: {0:0.##}\n", result);
}
catch (Exception e)
{
Console.WriteLine("Oh no! An exception occurred trying to do the math.\n - Details: " + e.Message);
}
Console.WriteLine("------------------------\n");
// Wait for the user to respond before closing.
Console.Write("Press 'n' and Enter to close the app, or press any other key and Enter to continue: ");
if (Console.ReadLine() == "n") endApp = true;
Console.WriteLine("\n"); // Friendly linespacing.
}
return;
}
}
下一步
繼續進行本教學課程的第二個部分: