我有如下界面
public interface IMyInterface
{
// Some method and property signatures
}
我有以下实现上述接口(interface)的类
public class MyClass : IMyInterface
{
// Some methods and properties as declared by IMyInterface
}
然后我在某个随机类中有这个方法,我想返回一个实现 IMyInterface
的对象列表。在这个特定的实现中,这些对象是 MyClass
的实例。
public List<IMyInterface> getItems(int id)
{
return new List<MyClass>();
}
这将导致编译错误(在 Visual Studio 中实时可见)
Cannot implicitly convert type 'System.Collections.Generic.List<MyClass>' to 'System.Collections.Generic.List<IMyInterface>'
我在网上搜索了一下,终于找到了这个帖子 C# Interfaces and Generic Lists 然后我用下面的方法结束了
public List<IMyInterface> getItems(int id)
{
return new List<MyClass>().Cast<IMyInterface>().ToList();
}
这会编译,但对我来说这似乎是一种非常奇怪的处理方式;将具体类转换为接口(interface)。在线程中C# Interfaces and Generic Lists Aequitarum Custos 对已接受答案的评论表明不必这样做。
我是不是遗漏了什么,或者这是这样做的方法吗?
最佳答案
因为即使Base
是 Parent
的子类型, 并不意味着 List<Base>
是 List<Parent>
的子类型. IList<T>
在其通用参数方面是不变的,List<T>
也是如此(c# 不支持类变体,只支持接口(interface)变体)。
在这里阅读更多关于协变、逆变和不变的信息:http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx
如果List<T>
是协变的,你可以这样做:
List<Parent> list = new List<Base>();
如果你这样做会发生什么?
list.Add(new OtherBase());
这在编译时肯定是合法的,但会导致运行时错误。
关于c# - 为什么方法不能声明返回类型 `List<IMyInterface>` 并返回实现它的具体类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21307099/