首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 泛型深入學習實例(四):方法覆寫與約束基礎

     編輯:關於C語言

前言

本文探討泛型方法覆寫規則,並系統介紹四種顯式約束:基類、介面、建構函式、值/參考型別。

泛型方法覆寫規則


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 子句。

四大顯式約束詳解

1. 基類約束 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 成員
}

2. 介面約束 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(); }
}

3. 建構函式約束 where T : new()


class Factory where T : new()
{
    public T Create() => new T(); // 呼叫無參數建構函式
}

4. 值型別/參考型別約束


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、型別檢查與優化。
  • C# **不支援** C++ 概念的隱式簽名約束(如要求 T 有 + 運算子)。

結語

掌握泛型方法覆寫規則與四大約束,是設計泛型 API 的基石。下一篇將介紹泛型方法、委派、多載解析與重載限制。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved