C++/CLI Collections: |
|
Introduction |
While it provides the minimum functionality of a collection, the ICollection interface is not equipped to perform the regular operations of a collection class, such as adding, retrieving, or deleting items from a set. To assist you with creating a class as complete as possible, the .NET Framework provides an interface named IList. The IList interface, defined in the System::Collections namespace, is equipped with the methods necessary to add, insert, delete, or retrieve items from a collection. Because the functionalities of these methods may not suit you, to use these features, you must create a class that implements them. |
As mentioned above, to create a collection, you can derive it from the IList interface. Here is an example: using namespace System::Collections; public ref class CStudents : public IList { }; This IList interface is declared as follows: public interface class IList : ICollection, IEnumerable This means that the IList interface extends both the ICollection and the IEnumerable interfaces. This also implies that you must implement the members of these parent interfaces. In other words, you must implement the Count property, the SyncRoot property, the IsSynchronized property, and the CopyTo() method of the ICollection interface. From what we learned with ICollection, here are examples of implementing these members: public ref class CObjects : public IList { private: int items; array<Object ^> ^ objects; public: CObjects(); virtual property int Count { int get() { return items; } } virtual property bool IsSynchronized { bool get() { return false; } } virtual property Object ^ SyncRoot { Object ^ get() { return this; } } virtual void CopyTo(Array ^, int); }; CObjects::CObjects() { items = 0; objects = gcnew array<Object ^>(5); } void CObjects::CopyTo(Array ^ ary, int index) { } You must also implement the GetEnumerator() method of the IEnumerable interface. If you don't have time to completely implement it, you can simply return nullptr. Here is an example: using namespace System; using namespace System::Collections; public ref class CObjects : public IList { . . . No Change public: . . . No Change virtual void CopyTo(Array ^, int); virtual IEnumerator ^ GetEnumerator(void); }; CObjects::CObjects() { items = 0; objects = gcnew array<Object ^>(5); } IEnumerator ^ CObjects::GetEnumerator(void) { return nullptr; }
|
|
||
Home | Copyright © 2007-2013, FunctionX | Next |
|