通用包装对象列表

时间:2014-11-07 13:19:39

标签: c# list generics unity3d

有人能告诉我为什么我不能在列表中添加包含具有继承的泛型类的包装器吗?

public abstract class SectorObject{} 
public class SpawnPoint : SectorObject
public class Trigger : SectorObject
public class SectorObjectList<T>  where T : SectorObject { public List<T> items ; };


public List<SectorObjectList<SectorObject>> objectLists = new List<SectorObject< SectorObject>>();

SectorObjectList <SpawnPoint> spawnPoints = new SectorObjectList<SpawnPoint>();

objectLists.Add(spawnPoints);  // This line doesn't work.

它只能这样:

public List<SectorObjectList<SpawnPoint>> objectLists = new List<SectorObject< SpawnPoint>>();
SectorObjectList <SpawnPoint>spawnPoints = new SectorObjectList<SpawnPoint>();
objectLists.Add(spawnPoints);  

干杯。

1 个答案:

答案 0 :(得分:1)

经典协方差/逆变问题。你可以在Stack Overflow上找到很多相关的帖子,like this one。如果没有强制转换和转换,您应该使用抽象类进行声明,并使用具体类进行初始化:

List<SectorObjectList<SectorObject>> objectLists = 
    new List<SectorObjectList<SectorObject>>();
SectorObjectList<SectorObject> spawnPoints = new SectorObjectList<SectorObject>();
spawnPoints.items = new List<SectorObject>();
spawnPoints.items.Add(new SpawnPoint());
objectLists.Add(spawnPoints);

如果您的SectorObjectList明确绑定到SpawnPoint,那么您可以放弃投射适应者:

var spawnPoints2 = new SectorObjectList<SpawnPoint>() { 
    items= new List<SpawnPoint>()};
var spawnPointsCopy = new SectorObjectList<SectorObject>() { items= spawnPoints2.items.Cast<SectorObject>().ToList() };
objectLists.Add(spawnPointsCopy);