萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 泛型類別與介面定義深度解析:約束、多型別與最佳實踐

前言

泛型是 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 : classT 必須是參考型別(類別、介面、委派、陣列)
where T : structT 必須是實值型別(排除 Nullable)
where T : new()T 必須有公用無參數建構函式
where T : BaseClassT 必須繼承自 BaseClass
where T : IInterfaceT 必須實作 IInterface
where T : UT 必須衍生自另一個型別參數 U
where T : notnullC# 8.0+:T 不可為可為 null 型別
where T : unmanagedC# 7.3+:T 為非受控型別(無指標欄位的實值型別)
where T : defaultC# 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
}

四、實戰常見模式

Repository 模式基底類別

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)];
}

五、避坑指南

  1. 忘記加 where T : class 導致 new List<T>()、default(T) 比較等編譯失敗。
  2. 值型別與參考型別混用:struct 不能用 class 約束,反之亦然。
  3. 介面約束循環依賴:where T : IComparable<T> 等遞迴約束需謹慎設計。
  4. 共變異數/反變異數:out T(共變)、in T(反變)用於介面/委派,類別不支援。

總結

泛型約束是釋放泛型威力的關鍵。記住:越嚴格的約束,能在類別內部呼叫的成員越多(如 class 允許 new()、== null 比較;IComparable<T> 允許排序)。善用多型別參數與介面約束,打造高內聚、低耦合、型別安全的元件庫。

copyright © 萬盛學電腦網 all rights reserved