使用純文字編輯器和 C 編譯器建立控制檯應用程式

為了使用純文字編輯器建立用 C#編寫的控制檯應用程式,你需要 C#編譯器。C#編譯器(csc.exe)可以在以下位置找到:%WINDIR%\Microsoft.NET\Framework64\v4.0.30319\csc.exe

注意: 根據系統上安裝的 .NET Framework 版本,你可能需要相應地更改上面的路徑。

儲存程式碼

本主題的目的不是教你如何編寫一個控制檯應用程式,而是教你如何編譯一個[生成一個可執行檔案],除了 C#編譯器和任何純文字編輯器(如記事本)。

  1. 使用鍵盤快捷鍵 Windows Key + 開啟執行對話方塊 R
  2. 輸入 notepad,然後點選 Enter
  3. 將下面的示例程式碼貼上到記事本中
  4. 將檔案另存為 ConsoleApp.cs,方法是轉到檔案另存為… ,然後在’檔名’文字欄位中輸入 ConsoleApp.cs,然後選擇 All Files 作為檔案型別。
  5. 點選 Save

編譯原始碼

1.使用 Windows Key + R
2 開啟執行對話方塊。輸入:

%WINDIR%\Microsoft.NET\Framework64\v4.0.30319\csc.exe /t:exe /out:"C:\Users\yourUserName\Documents\ConsoleApp.exe" "C:\Users\yourUserName\Documents\ConsoleApp.cs"

現在,回到最初儲存 ConsoleApp.cs 檔案的位置。你現在應該看到一個可執行檔案(ConsoleApp.exe)。雙擊 ConsoleApp.exe 將其開啟。

而已! 你的控制檯應用程式已編譯。已建立可執行檔案,你現在擁有一個可用的控制檯應用程式。

using System;

namespace ConsoleApp
{
    class Program
    {
        private static string input = String.Empty;

        static void Main(string[] args)
        {
            goto DisplayGreeting;

            DisplayGreeting:
            {
                Console.WriteLine("Hello! What is your name?");

                input = Console.ReadLine();

                if (input.Length >= 1)
                {
                    Console.WriteLine(
                        "Hello, " + 
                        input + 
                        ", enter 'Exit' at any time to exit this app.");

                    goto AwaitFurtherInstruction;
                }
                else
                {
                    goto DisplayGreeting;
                }
            }

            AwaitFurtherInstruction:
            {
                input = Console.ReadLine();

                if(input.ToLower() == "exit")
                {
                    input = String.Empty;

                    Environment.Exit(0);
                }
                else
                {
                    goto AwaitFurtherInstruction;
                }
            }
        }
    }
}