首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

撰寫第一支 C# 程式:Hello World 進階版、編譯執行、註解與格式化輸出

     編輯:關於C#

Welcome 程式:互動式問候

using System;
class Welcome {
    static void Main() {
        Console.WriteLine("Please enter your name:");
        string name = Console.ReadLine();
        Console.WriteLine("Welcome to you, {0}!", name);
    }
}

程式碼逐行解析

1. 命名空間引入

using System;

匯入 System 命名空間,得以直接使用 Console 等類別。未引入時需寫完整名稱 System.Console。

2. 類別與 Main 方法

  • C# 程式碼必須包裹在類別中,無全域函式/變數。
  • Main() 為程式進入點,必須為 static,回傳 void 或 int。
  • 大小寫敏感。

3. 輸入/輸出

方法用途換行
Console.WriteLine輸出並換行是
Console.Write輸出不換行否
Console.ReadLine讀取一行文字含換行
Console.Read讀取單一字元代碼否

4. 格式化輸出

Console.WriteLine("Welcome {0} times, {1} and {2}!", x, name1, name2);
  • {0}, {1} 為佔位符,對應後續參數。
  • 最多支援 3 個參數(舊版),新版無上限。

命令列編譯與執行

csc Welcome.cs           // 產生 Welcome.exe
csc /out:MyApp.exe Welcome.cs  // 指定輸出檔名
csc /target:library Util.cs    // 產生 DLL
csc /?                   // 顯示所有選項

C# 編譯器直接產生 EXE/DLL,無獨立連結步驟(不同於 C/C++)。

註解風格

// 單行註解
/* 多行
   註解 */
  • 避免在 // 後使用 \(續行符會導致下一行也被註解)。
  • /* */ 不可巢狀,建議用 #if false ... #endif 暫時停用含註解的程式碼區塊。

字串操作基礎

string s = "Good" + "Morning"; // 串接
char c = s[3];                 // 索引存取,得 'd'
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved