介面定義與實作
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 抽象類別