泛型是 C# 2.0 引入的核心特性,讓類別、介面、方法能以「型別參數」延遲具體型別決定,實現程式碼重用與型別安全。本文從基礎語法進階到約束條件、多型別參數、介面繼承鏈等實戰主題,並釐清常見編譯錯誤成因。
public abstract class GetDataBase<T> : IHttpHandler, IRequiresSessionState
{
protected abstract T GetModel(HttpContext context);
protected abstract IList<T> GetList(int pageSize, int pageIndex, string where,
string sortName, string sortOrder, out int total);
protected JsonFlexiGridData GetFlexiGridData(IList<T> list, int pageIndex,
int pageSize, int total,
string colKey, string colsInfo)
{
var pl = new PagedList<T>();
pl.PageIndex = pageIndex - 1;
pl.PageSize = pageSize;
pl.DataList = new List<T>(); // 編譯錯誤:T 未限制為 class
pl.DataList.AddRange(list);
pl.Total = total;
return JsonFlexiGridData.ConvertFromPagedList(pl, colKey, colsInfo.Split(','));
}
}
new List<T>() 需要 T 為**參考型別**(class),否則無法隱式轉換。加上 where T : class 約束即可。
public abstract class GetDataBase<T> : IHttpHandler, IRequiresSessionState
where T : class // 關鍵:限定 T 必須是類別(參考型別)
{
// ...
}
| 約束 | 說明 |
|---|---|
where T : class | T 必須是參考型別(類別、介面、委派、陣列) |
where T : struct | T 必須是實值型別(排除 Nullable) |
where T : new() | T 必須有公用無參數建構函式 |
where T : BaseClass | T 必須繼承自 BaseClass |
where T : IInterface | T 必須實作 IInterface |
where T : U | T 必須衍生自另一個型別參數 U |
where T : notnull | C# 8.0+:T 不可為可為 null 型別 |
where T : unmanaged | C# 7.3+:T 為非受控型別(無指標欄位的實值型別) |
where T : default | C# 9.0+:覆寫繼承而來的約束 |
// IDeviceAgent 繼承 IObjectWithKey<TK>
public interface IDeviceAgent<TK, TCk> : IObjectWithKey<TK>, IDisposable
{
// ...
}
// TV 必須實作 IObjectWithKey<TK>
public interface IContainer<TK, TV> where TV : IObjectWithKey<TK>
{
// ...
}
public abstract class GetDataBase<TListItem, TModel> : IHttpHandler, IRequiresSessionState
where TListItem : class
where TModel : class
{
// 兩個型別參數各自約束為 class
}
public abstract class Repository<TEntity, TKey> where TEntity : class, IEntity<TKey>
{
protected readonly DbContext Context;
public Repository(DbContext ctx) { Context = ctx; }
public virtual TEntity GetById(TKey id) => Context.Set<TEntity>().Find(id);
public virtual void Add(TEntity entity) => Context.Set<TEntity>().Add(entity);
}
public interface IStrategy<TInput, TOutput>
{
TOutput Execute(TInput input);
}
public class StrategyFactory
{
private readonly Dictionary<Type, object> _strategies = new();
public void Register<TIn, TOut>(IStrategy<TIn, TOut> s) => _strategies[typeof(TIn)] = s;
public IStrategy<TIn, TOut> Resolve<TIn, TOut>() => (IStrategy<TIn, TOut>)_strategies[typeof(TIn)];
}
where T : class 導致 new List<T>()、default(T) 比較等編譯失敗。struct 不能用 class 約束,反之亦然。where T : IComparable<T> 等遞迴約束需謹慎設計。out T(共變)、in T(反變)用於介面/委派,類別不支援。泛型約束是釋放泛型威力的關鍵。記住:越嚴格的約束,能在類別內部呼叫的成員越多(如 class 允許 new()、== null 比較;IComparable<T> 允許排序)。善用多型別參數與介面約束,打造高內聚、低耦合、型別安全的元件庫。