C# 是微軟推出的現代、型別安全、物件導向程式語言,語法繼承自 C/C++,設計吸收了 Java、Delphi、VB 優點,目標是結合 VB 開發效率與 C++ 執行效能。本文從最基礎的 Hello World 切入,詳細解析程式結構、命名空間、編譯執行流程、基本語法元素,為零基礎學習者建立清晰認知框架。
// idontlikeHelloworld.cs
using System;
class IDontLikeHelloWorld {
static void Main() {
Console.WriteLine("I don't like Hello World");
Console.ReadLine(); // 防止控制台即刻關閉
}
}
csc.exe 編譯器)
csc idontlikeHelloworld.cs
// 產生 idontlikeHelloworld.exe
.c 可用 VC++ IDE 編輯,csc 同樣編譯| 行 | 代碼 | 解析 |
|---|---|---|
| 1 | using System; | 匯入 System 命名空間,後續可直接用 Console 而非 System.Console |
| 2 | class IDontLikeHelloWorld | 定義類別,C# 程式碼必須在類別/結構內 |
| 3 | { | 類別主體開始 |
| 4 | static void Main() | 程式進入點:static(無需實例)、void(無回傳)、Main(固定名稱) |
| 5 | Console.WriteLine(...) | 呼叫 System.Console 類別的靜態方法,輸出字串並換行 |
| 6 | Console.ReadLine() | 等待使用者按 Enter,否則主控台視窗一閃而過 |
| 7 | } | Main 結束 |
| 8 | } | 類別結束 |
// 語法
namespace [名稱] { 命名空間主體 }
// 範例
namespace MyApp {
class Program { static void Main() { } }
}
// 使用
using MyApp; // 匯入整個命名空間
using Sys = System; // 別名(解決衝突/簡化長名稱)
關鍵點:
using 僅是編譯器捷徑,不影響輸出 IL、不載入組件using 時需寫完整名稱:System.Console.WriteLinecsc.exe 自動參考 mscorlib.dll (核心類別庫),其他組件需 /r:Assembly.dll| 特性 | C/C++ | C# |
|---|---|---|
| 範圍解析 | :: (命名空間/類別/全域) | 統一用 . (命名空間.類別.成員) |
| 指標/間接 | *、&、-> | 僅 unsafe 區塊允許,99% 代碼不用 |
| 前置宣告 | 需 #include、標頭檔 | 無需宣告,直接使用,編譯器解析中繼資料 |
| 主程式 | int main() 全域函式 | static void Main() 在類別內 |
| 大小寫敏感 | 是 | 是 |
Consoleusing 匯入的命名空間System.ConsoleWriteLine(string),發出 IL call 指令mscorlib.dll,JIT 編譯執行using System; → CS0103: 名稱 'Console' 不存在於目前內容中Main 拼錯大小寫 → CS5001: 程式沒有適合的靜態 'Main' 方法Console.ReadLine() → 主控台一閃而過以為沒執行C# 程式結構:using → namespace → class → static void Main()。編譯器 csc.exe 將原始碼編譯為 IL 組件,CLR 執行時 JIT 為機器碼。命名空間與 using 解決了 C/C++ 標頭檔地獄,中繼資料取代前置宣告。下一課將進入型別系統:值類型 vs 參考類型、簡單類型、列舉、結構、類別、介面、委派、陣列。