本文彙整 C# 基礎語法、陣列、集合介面、類別設計、運算子多載、屬性、介面等核心知識點,適合初學者建立完整概念地圖,也供資深開發者快速回顧。
out vs ref// out:呼叫端無需初始化,被呼叫端必須指派
void GetValues(out int a, out int b) { a = 1; b = 2; }
// ref:呼叫端必須初始化,雙向傳遞
void Swap(ref int x, ref int y) { int t = x; x = y; y = t; }
using 區塊:確定性釋放資源using (Font f = new Font("Arial", 10f))
{
// 區塊結束自動呼叫 f.Dispose()
}
const int MaxSize = 100;
enum Color { Red = 1, Green = 2, Blue = 4 }
int c = (int)Color.Red; // 顯式轉型取得底層值
string line = Console.ReadLine();
int num = Convert.ToInt32(line);
double d = double.Parse(textBox.Text);
Application.DoEvents(); // 處理待決訊息(慎用)
int[] a = new int[5]; // 預設值 0
int[] b = new int[] { 1, 2, 3 };
int[] c = { 4, 5, 6 }; // 隱含型別
foreach (int v in c) { ... }
for (int i = 0; i < c.Length; i++) { ... }
int[,] rect = new int[3, 4]; // 矩形陣列
int[,] rect2 = { {1,2}, {3,4}, {5,6} }; // 初始化
int[][] jagged = new int[3][]; // 階梯陣列
jagged[0] = new int[] { 1, 2 };
jagged[1] = new int[] { 3, 4, 5 };
params 參數陣列
void Sum(params int[] values) { ... }
Sum(1, 2, 3, 4); // 呼叫端可直接傳入多個引數
| 介面 | 關鍵成員 | 用途 |
|---|---|---|
IEnumerable | GetEnumerator() | 支援 foreach |
IEnumerator | MoveNext(), Current, Reset() | 迭代器模式核心 |
IComparable | CompareTo(obj) | 型別內建排序邏輯 |
al.Add(obj);
al.Remove(obj);
al.Clear();
al.Reverse();
al.Sort(); // 需元素實作 IComparable
public // 完全公開
private // 僅類別內部
protected // 衍生類別可見
internal // 同組件可見
protected internal // 衍生類別或同組件
static int Count; // 類別層級,必須在類別中初始化
this.Property = value; // 實例參考
class Base { public virtual void Show() { } }
class Derived : Base { public override void Show() { } }
public struct Roman
{
public int Value;
// 隱式轉換:int -> Roman
public static implicit operator Roman(int v) => new Roman { Value = v };
// 顯式轉換:float -> Roman
public static explicit operator Roman(float v) => new Roman { Value = (int)v };
// 運算子多載
public static Roman operator +(Roman a, Roman b) => new Roman { Value = a.Value + b.Value };
}
private int _age;
public int Age
{
get => _age;
set => _age = value; // value 為隱含參數
}
interface IA { void Do(); }
class A : IA { public void Do() { } }
// 型別測試
if (obj is IA ia) ia.Do(); // 模式比對 (C# 7+)
IA ia2 = obj as IA;
if (ia2 != null) ia2.Do();
interface IAA : IA { float F { get; set; } }
class C : IA, IAA { ... } // 逗號分隔實作多個介面
C# 以強型別、物件導向、垃圾回收為核心,語法簡潔而強大。掌握上述基石,即可輕鬆進階至 LINQ、非同步程式設計、泛型等高階主題。建議配合實際撰寫小專案,將語法內化為肌肉記憶。