给出以下类型:
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>();
这导致以下编译错误:
Argument type ‘System.Collections.Generic.List’ is not assignable to parameter type ‘System.Collections.Generic.List’
我明白错误,我意识到有解决方法.我只是看不到任何明确的原因,直接转换是不允许的.包含在ISecondary列表中的值应该完全是IPrimary类型的(扩展)值.然后列表< IPrimary>列表< 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){ } }
解决方法
Why can I not do this?
List<IPrimary> list = new List<ISecondary>();
想像你有一个这样定义的方法:
public void PopulateList(List<IPrimary> listToPopulate) { listToPopulate.Add(new Primary()); // Primary does not implement ISecondary! }
如果你要传递一个List< ISecondary>作为参数?