【发布时间】:2014-01-10 09:40:38
【问题描述】:
这很奇怪,我试图在我的构造函数中使用 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?)
我看不出两者之间的区别。我要疯了,试图弄清楚这一点。有什么想法吗?
【问题讨论】:
-
您正在尝试将
BookedCateringItem的列表分配给CateringItem的集合。类型不匹配 - 这就是区别 -
什么是 BookedCateringItem?尝试新的 List
() -
你需要阅读
Covariance。见tomasp.net/blog/variance-explained.aspx -
我太笨了!谢谢! :D
-
@haim770 我认为这是关于 ICollection 和 List 的兼容性,我太专注于我忽略了我试图初始化的列表的类型。
标签: c#