I am writing a library that displays a bunch of child objects on the screen. The child object is abstract, and it is intended for users of this library to get their own child from this abstract class.
public abstract class Child : IRenderable {} public interface IParent<T> where T : Child { IEnumerable<T> Children { get; } }
The complication is that I do not have an IParent list to work with; instead, I have an IRenderables group. The library user is expected to write something like this:
public class Car : IRenderable { } public class Cow : IRenderable, IParent<Calf> { } public class Calf : Child { }
In Draw (), the library needs to drop and check if the IRenderable is also IParent. However, since I do not know about the calf, I do not know what to abandon the cow.
// In Draw() foreach(var renderable in Renderables) { if((parent = renderable as IParent<???>) != null) // what to do? { foreach(var child in parent.Children) { // do something to child here. } } }
How can I solve this problem? Is this something in common with covariant generics or something else (I'm not familiar with the concept of covariance)?
Jake
source share