本文介紹泛型方法宣告與呼叫、泛型方法多載限制、泛型委派與型別推斷。
public class Finder
{
// 泛型方法:型別參數在方法層級宣告
public static int Find(T[] items, T item)
{
for (int i = 0; i < items.Length; i++)
if (items[i].Equals(item)) return i;
return -1;
}
}
// 呼叫:型別引數可省略(編譯器推斷)
int idx = Finder.Find(new[] { 1, 3, 5, 7 }, 5); // 推斷 T = int
class Demo
{
// 錯誤:僅型別參數名稱不同,無法構成多載
void M1(T[] a) { }
void M1(U[] a) { }
// 正確:非泛型參數不同
void M2(int x) { }
void M2(string s) { }
// 錯誤:約束不同不構成多載
void M3(T t) where T : ClassA { }
void M3(T t) where T : ClassB { }
}
delegate bool Predicate(T value);
class Program
{
static bool IsPositive(int i) => i > 0;
static bool IsLong(string s) => s.Length > 10;
static void Main()
{
Predicate p1 = IsPositive;
Predicate p2 = IsLong;
// 或使用 Lambda
Predicate p3 = d => d > 0.5;
}
}
Func、Action 等內建委派大幅簡化泛型回呼程式碼。
// 協變(out):回傳型別可向基類轉換
delegate TResult Func();
// 逆變(in):參數型別可向衍生類轉換
delegate void Action(T arg);
C# 4.0 引入委派變異性,配合 in/out 關鍵字,增強泛型委派靈活度。
泛型方法與委派是 C# 函數式程式設計的核心工具。理解多載解析規則、型別推斷與變異性,能設計出更具表達力的 API。