我有一個基類ScenBase和派生類ScenC。我有一個從基類Hex中派生的類HexC。我也有一個來自基類Unit的類UnitC。我可以設置十六進制的數組指向HexC數組,但是編譯器不會讓我設置單位的名單指向UnitC列表:C#:的<T>列表=列表<源自T>不編譯
// 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>
後面的「是」隱式轉換規則時,但我可以設置爲陣列
C#不支持類的協變性。而在集合上它也不是類型安全的。 – CodesInChaos