C#泛型和接口以及简单的OO

Dan*_*iil 5 c# oop generics

我的C#技能很低,但我无法理解为什么以下失败:

public interface IQuotable {}
public class Order : IQuotable {}
public class Proxy {
  public void GetQuotes(IList<IQuotable> list) { ... }
}
Run Code Online (Sandbox Code Playgroud)

然后代码如下:

List<Order> orders = new List<Orders>();
orders.Add(new Order());
orders.Add(new Order());

Proxy proxy = new Proxy();
proxy.GetQuotes(orders); // produces compile error
Run Code Online (Sandbox Code Playgroud)

我只是做错了什么而没有看到它?由于Order实现了Quotable,因此订单列表将作为可分配的IList.我有类似Java的东西,它的工作原理,所以我很确定它缺乏C#知识.

Jon*_*eet 12

你无法从a转换List<Order>IList<IQuotable>.他们只是不兼容.毕竟,你可以添加任何类型IQuotableIList<IQuotable>- 但你只能添加一个Order(或子类型)List<Order>.

三种选择:


Mir*_*Mir 9

IList是不协变的.你不能投了List<Order>一个IList<Quotable>.

您可以将签名更改GetQuotes为:

public void GetQuotes(IEnumerable<IQuotable> quotes)
Run Code Online (Sandbox Code Playgroud)

然后,通过以下方式实现列表(如果需要其功能):

var list = quotes.ToList();
Run Code Online (Sandbox Code Playgroud)