本文介绍了“虚拟列表”在C#避免typecasting在继承类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个抽象类 Player 。类 GameAPlayer GameBPlayer 继承自 Player 。反过来,一对抽象类继承自 GameAPlayer GameBPlayer

Let's say I've got an abstract class called Player. Classes GameAPlayer and GameBPlayer inherit from Player. In turn, a couple of abstract classes inherit from GameAPlayer and GameBPlayer respectively.

假设我有另一个抽象类 Engine ,它拥有 List< Player> 。类 GameAEngine GameBEngine 都继承自 Engine 。我知道一个事实, GameAEngine 中的所有玩家都将是 GameAPlayer 类型,所有玩家 GameBEngine 的类型为 GameBPlayer

Let's say I've got another abstract class called Engine which hosts List<Player>. Classes GameAEngine and GameBEngine both inherit from Engine. I know for a fact that all players in GameAEngine will be of type GameAPlayer, and that all players in GameBEngine will be of type GameBPlayer.

我无法将列表< Player> 移动到 GameAEngine GameBEngine ,因为我使用 Engine 本身的列表。

I cannot move List<Player> into GameAEngine and GameBEngine as I'm using the list in Engine itself.

已将类型转换玩家插入 GameAPlayer GameBPlayer 每次我使用列表在他们各自的引擎只是似乎不清洁。

Having to typecast Player into GameAPlayer and GameBPlayer every time I use the list in their respective engines just seems unclean. Is there any way I can avoid having to do this?

推荐答案

更改引擎 Engine< TPlayer>其中TPlayer:Player

请注意,这将使基本引擎在任何地方都需要通用类型参数;

Change Engine to Engine<TPlayer> where TPlayer : Player.
Note that this will make base engines require generic type parameters everywhere; you can work around that using a non-generic interface.

或者,在派生类中创建一个 GetPlayer 方法这样做,并使用它而不是基本列表。

Alternatively, make a GetPlayer method in the derived classes that does the cast, and use that instead of the base list.

这篇关于“虚拟列表”在C#避免typecasting在继承类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 15:56