c# - 无论泛型类型如何,如何声明一个列表使其包含一个泛型类?
问题描述
我正在寻找一种方法来声明一个可以包含任何泛型类实例的列表,无论这些实例的泛型类型如何。也许是一种无需指定类的泛型类型即可声明 List 的方法?
public class Character {}
public class Hero : Character {}
public class Creature : Character {}
public abstract class ActorController<T> where T : Character
{
protected T actor;
}
public class CharacterController : ActorController<Character> {}
public class HeroController : ActorController<Hero> {}
public class CreatureController : ActorController<Creature> {}
public class Zone
{
// If it is even possible, what should I put instead of the ???
// so the List understands that the generic type doesn't matter
// and that I want any type of ActorController in it ?
private List<ActorController<???>> actorControllers;
}
我指定我试图避免声明将用作ActorController父级的常规类或接口,因为这样做我会失去拥有动态Actor属性的兴趣。
提前谢谢你,如果我误用了行话,我很抱歉。
解决方案
你可以为它创建一个协变接口:
public interface IActorController<out T> where T : Character {
}
然后ActorController<T>
实现该接口:
public abstract class ActorController<T> : IActorController<T> where T : Character
{
protected T actor;
}
然后你可以让你的列表是 type List<IActorController<Character>>
,你可以添加任何类型:
public class Zone
{
public List<IActorController<Character>> actorControllers;
}
/* ... */
var heroController = new HeroController();
var creatureController = new CreatureController();
myZone.actorControllers.Add(heroController);
myZone.actorControllers.Add(creatureController);
您只需要确保要在列表成员上使用的任何内容都在界面中(或强制转换)
简单证明(根据您的代码,稍作修改以显示一些结果):https ://dotnetfiddle.net/KY2pMP (更新后也显示正确的Character
继承)
推荐阅读
- c# - 如何在自定义类中使用 .Net Core Dependency Injection
- android - 图像尺寸太大而无法传递给另一个活动(数组 byteArray )对于高质量图像来说太大)
- windows - 在 Perl 中使用 DBI 连接到 Oracle 数据库,在 Windows 中出现 ERROR OCIEnvNlsCreate
- python - 我的二分法程序中的问题
- android - Android 应用操作:语音/文本调用
- jenkins - 无法从 Jenkins 管道的当前阶段获取日志
- http - Adodb 连接到带有 https 地址的访问数据库
- c++ - 在字符串 C++ 中查找倒数第二个单词
- python - /srv/share/ykant3/pythia/vector_cache/wiki.en.bin 无法打开加载
- python - Python调度-如何每5分钟从HTML中提取数据