掌握 C# 基本語法是踏上 .NET 開發旅程的第一步。本文涵蓋程式基本結構、命名慣例、關鍵字、註解、Main 方法、編譯執行流程,並提供實用的程式碼風格建議。
// 1. using 指令:引入命名空間
using System;
// 2. 命名空間宣告:邏輯分組
namespace HelloWorld {
// 3. 類別宣告
public class Program {
// 4. Main 方法:程式進入點
public static void Main() {
// 5. 陳述式
Console.WriteLine("Hello, World!");
}
}
}
.NET 6+ (C# 9+) 允許省略 Main、類別、命名空間:
// Program.cs 完整內容
using System;
Console.WriteLine("Hello, World!");
編譯器自動產生 Program 類別與 Main 方法。
C# 10+:
namespace MyApp; // 整個檔案屬於此命名空間,無需大括號
public class MyClass { }
| 元素 | 慣例 | 範例 |
|---|---|---|
| 命名空間 | PascalCase | MyCompany.MyProduct.Module |
| 類別/結構/介面/列舉/委派 | PascalCase | Customer, IRepository, OrderStatus |
| 方法/屬性/事件/公開欄位 | PascalCase | CalculateTotal, FirstName |
| 區域變數/參數 | camelCase | itemCount, userName |
| 私有欄位 | _camelCase | _firstName |
| 常數/readonly 靜態欄位 | PascalCase | MaxRetries |
| 型別參數 | T / TDescriptor | T, TKey, TValue |
規則:字母/底線開頭、可含字母/數字/底線、不可為關鍵字 (可加 @ 前綴)、區分大小寫。
abstract as base bool break byte case catch char checked class const
continue decimal default delegate do double else enum event explicit
extern false finally fixed float for foreach goto if implicit in int
interface internal is lock long namespace new null object operator out
override params private protected public readonly ref return sbyte sealed
short sizeof stackalloc static string struct switch this throw true try
typeof uint ulong unchecked unsafe ushort using virtual void volatile while
add alias ascending descending dynamic from get global group into join
let orderby partial remove select set value var when where yield
內容關鍵字在特定語境有特殊意義,其他地方可作識別碼 (如 var x = 1;)。
// 單行註解
/* 多行註解
可跨多行 */
///
/// XML 文件註解:產生 API 文件、IntelliSense 提示
///
/// 參數說明
/// 回傳值說明
public int Add(int x, int y) => x + y;
// 區域標記 (編輯器摺疊)
#region 初始化
// ...
#endregion
// 標準
static void Main() { }
// 回傳結束代碼
static int Main() { return 0; }
// 接收命令列參數
static void Main(string[] args) { }
static int Main(string[] args) { return 0; }
// 非同步 Main (C# 7.1+)
static async Task Main() { await DoWork(); }
static async Task Main(string[] args) { return await DoWorkAsync(); }
// 多 Main 進入點:編譯器選項 /main:TypeName 指定
; 結尾 (x = 1;, if (...) {}, return;)x + y, Method(), new Object())=> 簡化單行實作public int Add(int a, int b) => a + b; // 方法
public string Name { get => _name; set => _name = value; } // 屬性
public override string ToString() => $"Person: {Name}"; // 覆寫
# 建立專案
dotnet new console -n MyApp
cd MyApp
# 編譯 (產生 dll)
dotnet build
# 執行
dotnet run
# 發布獨立執行檔
dotnet publish -c Release -r win-x64 --self-contained true
csc Program.cs # 產生 Program.exe
csc /target:library Lib.cs # 產生 Lib.dll
csc /reference:Lib.dll App.cs # 參考組件
<Nullable>enable</Nullable>。using 指令放在命名空間內外有差別嗎?A: 放在 namespace 內僅影響該命名空間內的型別解析;放在外部影響整個檔案。慣例放在檔案最上方。
Main 方法嗎?A: 可以,但需用 /main 指定進入點。單一專案通常只有一個。
var 是關鍵字還是內容關鍵字?A: 內容關鍵字。在 var x = 1; 中為關鍵字;var var = 1; 中第二個 var 為識別碼 (不建議)。
A: 是。MyClass ≠ myclass ≠ MYCLASS。