问题
I have base classes like this:
public class Scene
{
public IList<SceneModel> Models {get; set;}
}
public class SceneModel { }
and derived classes like this:
public class WorldScene : Scene
{
public override IList<WorldModel> Models {get; set;}
}
public class WorldModel : SceneModel { }
So my question is, how do I manage this. As it stands the compiler isn't happy with this (and to be honest it looks a bit weird to me anyway). So is what I'm trying to do impossible? And if so, why? Or is it possible and I'm just going about it the wrong way?
回答1:
You can use generics
public class BaseScene<T>
where T : SceneModel
{
public IList<T> Models {get; set;}
}
public class Scene : BaseScene<SceneModel>
{
}
public class WorldScene : BaseScene<WorldModel>
{
}
Each type of scene will be parametrized by corresponding model type. Thus you will have strongly typed list of models for each scene.
回答2:
This is fundamentally impossible.
What would happen if you write
Scene x = new WorldScene();
x.Models.Add(new OtherModel());
You just added an OtherModel
to a List<WorldModel>
.
Instead, you should make the base class generic.
来源:https://stackoverflow.com/questions/13105154/override-listbaseclass-with-listderivedclass