I have a generic items list class to create a more specifi开发者_运维问答c listing using it as base class, something like this..
ref class ItemBase { }
ref class ItemA : ItemBase { }
ref class ItemList abstract {
public:
virtual void add(ItemBase ^p);
}
ref class ItemListA : ItemList {
public:
virtual void add(ItemA ^p) override; // it doesn't works :(
}
I want to restric adding specific type of items in each class.
The accepted pattern for doing this is making the base class method protected
:
ref class ItemBase { }
ref class ItemA : ItemBase { }
ref class ItemList abstract {
protected:
virtual void addInternal(ItemBase ^p);
}
ref class ItemListA : ItemList {
public:
virtual void add(ItemA ^p){addInternal(p);}
}
Here is a better solution using generics. Note how we constrain the generic parameter T
to ItemBase
, to enforce that this collection must only ne used with ItemBase
or its subclasses.
ref class ItemBase { };
ref class ItemA : public ItemBase { };
generic <class T>
where T: ItemBase
ref class ItemList abstract {
public:
virtual void Add(T p){}
};
ref class ItemListA : ItemList<ItemA^> {
//no need to override Add here
};
//usage
int main(array<System::String ^> ^args)
{
ItemListA^ list = gcnew ItemListA();
list->Add(gcnew ItemA());
}
精彩评论