override List<baseClass> with List<derivedClass>

雨燕双飞 提交于 2019-12-10 14:07:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!