gpt4 book ai didi

C#: 的列表 = 的列表不编译

转载 作者:太空宇宙 更新时间:2023-11-03 20:32:45 27 4
gpt4 key购买 nike

我有一个基类 ScenBase 和一个派生类 ScenC。我有一个从基类 Hex 派生的类 HexC。我还有一个从基类 Unit 派生的类 UnitC。我可以将一个 Hex 数组设置为指向一个 HexC 数组,但编译器不允许我将一个 List of Unit 设置为指向一个 UnitC 列表:

// The Core Database for the game scenario.
// Theoretically multiple secenarios can be loaded
// into memory at the same time.
[Serializable]
public class ScenC : ScenBase
{
public bool playable { get; set; }
public HexC[,] hexCs { get; private set; }
public List<UnitC> unitCs { get; private set; }

// A database for every user and AI entity.
public List<ScenV> chViews { get; private set; }
public List<string> characters { get; private set; }

public ScenC(int xDimI, int yDimI) : base (xDimI, yDimI)
{
playable = false;
chViews = new List<ScenV>();
characters = new List<string>();
characters.Add("Supreme");
hexCs = new HexC[xDim, yDim];
hexs = hexCs; //this line complies fine
newHex = (int x, int y) => new HexC(this, x, y);
unitCs = new List<UnitC>();

// **This line won't compile**
unitCs = units;
Init();
}
}

下面是基类 ScenBase 的字段属性:

[Serializable]
public abstract class ScenBase
{
public Hex[,] hexs;
public List<Unit> units { get; protected set; }
public DateTime currGameTime { get; set; }
public int xDim { get; set; }
public int yDim { get; set; }
public double scale { get; protected set; }
protected delegate Hex NewHex(int x, int y);
protected NewHex newHex;

//Rest of Class not shown for simplicity
}

为什么我不能设置 List<Hex>List<HexC>当它遵循“是一个”隐式转换规则时,但我可以将数组设置为数组

最佳答案

这是不可能的。

如果可能的话,您将能够向列表中添加不同的派生类型。
例如:

List<Car> cars = new List<Car>
List<Vehicle> vehicles = cars; //Error!
vehicles.Add(new Bicycle()); //That's not a car!

您要求的是协方差;它只适用于不可变接口(interface)(例如 IEnumerable<T> )

关于C#:<T> 的列表 = <Derived from T> 的列表不编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6641505/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com