覆盖List< baseClass>与List< derivedClass> [英] override List<baseClass> with List<derivedClass>

查看:79
本文介绍了覆盖List< baseClass>与List< derivedClass>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的基类:

public class Scene
{
    public IList<SceneModel> Models {get; set;}
}

public class SceneModel { }

以及类似的派生类:

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?

推荐答案

您可以使用泛型

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.

这篇关于覆盖List&lt; baseClass&gt;与List&lt; derivedClass&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆