本文探討泛型方法覆寫規則,並系統介紹四種顯式約束:基類、介面、建構函式、值/參考型別。
abstract class Base
{
public abstract T F(T t, U u) where U : T;
public abstract T G(T t) where T : IComparable;
}
class Derived : Base
{
// 合法:約束自動繼承,不可重複宣告
public override X F(X x, Y y) where Y : X { ... }
// 非法:覆寫時不可重新宣告約束
// public override T G(T t) where T : IComparable { ... } // 編譯錯誤
}
where 子句。where T : BaseClass
class Animal { public void Eat() {} }
class Dog : Animal { public void Bark() {} }
class Zoo where T : Animal
{
public void Feed(T animal) => animal.Eat(); // 可呼叫 Animal 成員
}
where T : IInterface
interface IPrintable { void Print(); }
interface IComparable { int CompareTo(T other); }
class Repository
where K : IComparable
where V : IPrintable
{
public void Add(K key, V value) { key.CompareTo(key); value.Print(); }
}
where T : new()
class Factory where T : new()
{
public T Create() => new T(); // 呼叫無參數建構函式
}
struct Point { public int X, Y; }
class Entity { public string Name; }
class ValueBox where T : struct { } // 僅限 struct、enum、primitive
class RefBox where T : class { } // 僅限 class、interface、delegate、array
T 僅能存取 object 成員(ToString、Equals 等)。T 擁有特定能力,啟用 IntelliSense、型別檢查與優化。T 有 + 運算子)。掌握泛型方法覆寫規則與四大約束,是設計泛型 API 的基石。下一篇將介紹泛型方法、委派、多載解析與重載限制。