c# - 为什么方法不能声明返回类型 `List<IMyInterface>` 并返回实现它的具体类

标签 c# generics return-type

我有如下界面

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 对已接受答案的评论表明不必这样做。

我是不是遗漏了什么,或者这是这样做的方法吗?

最佳答案

因为即使BaseParent 的子类型, 并不意味着 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/

相关文章:

c# - 如何将直接声音添加到 FilterGraph 2?

c# - 如何编写一个好的离线-在线调度程序

java - 将 ArrayList<Object> 作为参数传递给方法,处理 arrayList 并返回它 - Java

error-handling - Web API的返回类型,可轻松处理错误

java - 使用 java 泛型类型进行类型转换

java - 通用返回类型 - 为什么我不能这样做?

c# - 自定义属性的构造函数如何采用可选参数

C# 使用 Process.Start() 打开不可用的网络路径

c# - 分割用户名和密码凭证

generics - 如何避免将具体结构更改为通用结构所产生的链式 react ?