C#列表到ICollection

dpp*_*dpp 2 c#

这很奇怪,我试图在构造函数中使用List初始化我的ICollection,这种情况发生了:

Schedules = new List<BookingSchedule>(); //OK
CateringItems = new List<CateringItem>(); //Not
Run Code Online (Sandbox Code Playgroud)

属性:

public virtual ICollection<BookingSchedule> Schedules { get; set; }
public virtual ICollection<BookedCateringItem> CateringItems { get; set; }
Run Code Online (Sandbox Code Playgroud)

错误:

Error   1   Cannot implicitly convert type
'System.Collections.Generic.List<MyApp.Models.CateringItem>' to  
'System.Collections.Generic.ICollection<MyApp.Models.BookedCateringItem>'. 
An explicit conversion exists (are you missing a cast?)
Run Code Online (Sandbox Code Playgroud)

我看不出两者之间的区别.我疯了,想弄清楚这一点.任何的想法?

hel*_*elb 9

如果类型T1和T2相同List<T1>,ICollection<T2>则只能转换为.或者,您可以转换为非泛型ICollection

ICollection CateringItems = new List<CateringItem>(); // OK
Run Code Online (Sandbox Code Playgroud)


小智 3

yourCateringItems是 的集合BookedCateringItem,在初始化时,您初始化了 的列表CateringItem

显然他们不兼容...