首页 > 解决方案 > 无论泛型类型如何,如何声明一个列表使其包含一个泛型类?

问题描述

我正在寻找一种方法来声明一个可以包含任何泛型类实例的列表,无论这些实例的泛型类型如何。也许是一种无需指定类的泛型类型即可声明 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属性的兴趣。

提前谢谢你,如果我误用了行话,我很抱歉。

标签: c#listgenerics

解决方案


你可以为它创建一个协变接口:

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继承


推荐阅读