C# 僅支援顯式約束(保證型別安全),非強制。無約束時型別參數僅能存取 System.Object 成員。
四種約束類型:
class A { public void F1() {} }
class B { public void F2() {} }
class C
where S : A // S 繼承自 A
where T : B // T 繼承自 B
{
// 可在 S 型別呼叫 F1,T 型別呼叫 F2
}
interface IPrintable { void Print(); }
interface IComparable { int CompareTo(T v); }
interface IKeyProvider { T GetKey(); }
class Dictionary
where K : IComparable
where V : IPrintable, IKeyProvider
{
// K 可呼叫 CompareTo,V 可呼叫 Print 和 GetKey
}
class A { public A() {} }
class B { public B(int i) {} }
class C where T : new()
{
// 可使用 T t = new T();
}
C c1 = new C(); // OK,A 有無參建構函式
C c2 = new C(); // 錯誤,B 無無參建構函式
public struct A { }
public class B { }
class C where T : struct
{
// T 為值型別
}
C c1 = new C(); // OK
C c2 = new C(); // 錯誤,B 為參考型別
來源:李建忠老師講座投影片。