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

C++/CLI 介面與泛型完整教學:從 ICollection 到 List/Queue 多型與泛型集合

     編輯:VC 教學

介面定義與實作


using namespace System;

public interface class ICollection {
    void Put(Object^ o);
    Object^ Get();
};
  • 關鍵字 interface class(或 interface struct)。
  • 成員隱含 public abstract,無方法本體。
  • 慣例以 I 開頭大寫命名。
  • 支援多重繼承:interface class I3 : I1, I2。

類別實作介面


public ref class List : ICollection {
    ArrayList^ items = gcnew ArrayList;
public:
    virtual void Put(Object^ o) { items->Add(o); }
    virtual Object^ Get() {
        if (items->Count == 0) return nullptr;
        Object^ o = items[0];
        items->RemoveAt(0);
        return o;
    }
};

public ref class Queue : ICollection {
    System::Collections::Queue^ q = gcnew System::Collections::Queue;
public:
    virtual void Put(Object^ o) { q->Enqueue(o); }
    virtual Object^ Get() { return q->Count > 0 ? q->Dequeue() : nullptr; }
};

介面多型使用


ref class Item {};

void Process(ICollection^ c) {
    Item^ x = gcnew Item();
    c->Put(x);
    x = safe_cast(c->Get());
}

int main() {
    List^ l = gcnew List;
    Queue^ q = gcnew Queue;
    Process(l);
    Process(q);
}

泛型介面與類別


generic
public interface class IGenCollection {
    void Put(T item);
    T Get();
};

generic
public ref class GenList : IGenCollection {
    List^ items = gcnew List;
public:
    virtual void Put(T item) { items->Add(item); }
    virtual T Get() {
        if (items->Count == 0) return T(); // default(T)
        T t = items[0];
        items->RemoveAt(0);
        return t;
    }
};

泛型約束


generic
where T : IComparable
ref class SortedList { ... } // T 必須實作 IComparable

generic
where T : ref class, gcnew() // T 為參考型別且有無參建構子
ref class Factory { T Create() { return gcnew T(); } }

介面 vs 抽象類別

最佳實務

  • 定義契約用介面;共享實作用抽象類別。
  • 公開 API 盡量使用泛型介面(IEnumerable, IList)而非非泛型版本。
  • 實作介面時成員加 virtual(C++/CLI 要求)並考慮 sealed 防止進一步覆寫。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
特性介面抽象類別
多重實作支援單一繼承
預設實作C# 8.0+ default 方法,C++/CLI 不支援可提供
欄位/建構子不可有可有
存取修飾詞隱含 public可 protected/private