I’ve got a parent class Container that may contain any kind of Node, where Node is a subclass of a generic class specific to the parent, like so:
public class ContainerBase<NodeType, ObjectType>
where NodeType : NodeBase<ObjectType> where ObjectType : ObjectBase {
}
public abstract class NodeBase<T> where T : ObjectBase {
ContainerBase<NodeBase<T>, T> container;
public NodeBase(ContainerBase<NodeBase<T>, T> owner) {
container = owner;
}
}
What I want to do is create concrete subclasses for simplicity that implement standard object types:
public class ContainerNormal : ContainerBase<NodeNormal, ObjectNormal> {
}
public class NodeNormal : NodeBase<ObjectNormal> {
//This doesn't work
public NodeNormal(ContainerNormal owner) : base(owner) { }
}
I somewhat understand why the call to the base constructor doesn’t work. It’s trying to convert a ContainerNormal to a ContainerBase<NodeBase<ObjectNormal>, ObjectNormal> which doesn’t really work.
So what design pattern am I missing to make this work right? Or do I just have to take in a ContainerBase<NodeBase<ObjectNormal>,ObjectNormal> in the constructor, even though it may not necessarily be a ContainerNormal object?
Explore: Covariance and contravariance, but this should work: