Thursday, July 5, 2007

Implementing indexers in VC++

Unlike C#, C++ doesn't support indexers directly. However, we can achieve the same goal through a different way:

[System::Reflection::DefaultMemberAttribute(S"Item")]
public __gc class PlayoutLists : public ICollection
{
public:
ArrayList* listArray;
public:
PlayoutLists()
{
listArray = new ArrayList();
}
public:
__property PlayoutList* get_Item(int index)
{
return dynamic_cast(listArray->get_Item(index));
}
public: void CopyTo(Array* a, int index)
{
listArray->CopyTo(a, index);
}
public: __property int get_Count()
{
return listArray->get_Count();
}
public: __property Object* get_SyncRoot()
{
return listArray->get_SyncRoot();
}
public: __property bool get_IsSynchronized()
{
return false;
}
public: IEnumerator* GetEnumerator()
{
return listArray->GetEnumerator();
}
public: void Add(PlayoutList* newList)
{
listArray->Add(newList);
}
};

get_Item (and set_Item if you want to be able to set the value) property will work the same way as indexers in C#.

No comments: