如果我有這樣的代碼:非通用類的實現是不能繼承
public interface IThing<T> where T : class
{
// ...
}
public class BaseThing<T> : IThing<T> where T : class
{
// ...
}
public class ThingA : BaseThing<string>
{
// ...
}
public class ThingB : BaseThing<Uri>
{
// ...
}
此代碼失敗:
List<IThing<object>> thingList = new List<IThing<object>>();
thingList.Add(new ThingA());
thingList.Add(new ThingB());
即使ThingA
(間接)繼承自(應該是一個實例)IThing<T>
。爲什麼?是ThingA
/ThingB
不是IThing<T>
的實例嗎?
閱讀協變和逆變。 (除了知道這些概念是相關的,我並不知道回答這個問題的足夠的了。) – zimdanen
請注意,IThing的所有「實例」,如IThing ,IThing ,IThing