给定以下类型:
public interface IPrimary{ void doBattle(); }
// an ISecondary "is" an IPrimary
public interface ISecondary : IPrimary { }
// An implementation of ISecondary is also an IPrimary:
internal class SecondaryImpl : ISecondary
{
// Required, since this is an IPrimary
public void doBattle(){ }
}
为什么我不能这样做?
List<IPrimary> list = new List<ISecondary>();
这会导致以下编译错误:
参数类型“System.Collections.Generic.List”不可分配给参数类型“System.Collections.Generic.List”
我理解错误,并且我意识到有解决方法。我只是看不出为什么不允许这种直接转换的任何明确原因。ISecondary
毕竟,列表中包含的值应该是(通过扩展)类型的值。IPrimary
那么为什么会List<IPrimary>
被List<ISecondary>
解释为不相关的类型呢?
任何人都可以清楚地解释以这种方式设计 C# 的原因吗?
一个稍微扩展的示例:我在尝试执行类似于以下操作时遇到了这个问题:
internal class Program
{
private static void Main(string[] args)
{
// Instance of ISecondary, and by extention, IPrimary:
var mySecondaryInstance = new SecondaryImpl();
// This works as expected:
AcceptImpl(mySecondaryInstance);
// List of instances of ISecondary, which are also,
// by extention, instances of IPrimary:
var myListOfSecondaries = new List<ISecondary> {mySecondaryInstance};
// This, however, does not work (results in a compilation error):
AcceptList(myListOfSecondaries);
}
// Note: IPrimary parameter:
public static void AcceptImpl(IPrimary instance){ }
// Note: List of type IPrimary:
public static void AcceptList(List<IPrimary> list){ }
}