繁体   English   中英

C#列表到ICollection

[英]C# List to ICollection

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

Schedules = new List<BookingSchedule>(); //OK
CateringItems = new List<CateringItem>(); //Not

属性:

public virtual ICollection<BookingSchedule> Schedules { get; set; }
public virtual ICollection<BookedCateringItem> CateringItems { get; set; }

错误:

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?)

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

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

ICollection CateringItems = new List<CateringItem>(); // OK
    public virtual ICollection<BookedCateringItem> CateringItems { get; set; }
    CateringItems = new List<CateringItem>();

它是不同的类型,BookedCateringItem和CateringItem。 您需要将其中一个更改为另一个类型。

您的CateringItemsBookedCateringItem的集合,在初始化时,您初始化了CateringItem列表。

显然他们不兼容......

您希望将List<CateringItem>分配给ICollection<BookedCateringItem>所以您不能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM