C#列表到ICollection
这很奇怪,我正试图用构造函数中的列表初始化我的ICollection,结果如下:C#列表到ICollection,c#,C#,这很奇怪,我正试图用构造函数中的列表初始化我的ICollection,结果如下: Schedules = new List<BookingSchedule>(); //OK CateringItems = new List<CateringItem>(); //Not Schedules=newlist()//好啊 CateringItems=新列表()//不 特性: public virtual ICollection<BookingSchedule>
Schedules = new List<BookingSchedule>(); //OK
CateringItems = new List<CateringItem>(); //Not
Schedules=newlist()//好啊
CateringItems=新列表()//不
特性:
public virtual ICollection<BookingSchedule> Schedules { get; set; }
public virtual ICollection<BookedCateringItem> CateringItems { get; set; }
公共虚拟ICollection调度{get;set;}
公共虚拟ICollection 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?)
错误1无法隐式转换类型
“System.Collections.Generic.List”到
“System.Collections.Generic.ICollection”。
存在显式转换(是否缺少强制转换?)
我看不出两者之间的区别。我想弄明白这件事,真是疯了。有什么想法吗?您的
CateringItems
是BookedCateringItem
的集合,在初始化时,您初始化了CateringItem的列表
显然他们不兼容 公共虚拟ICollection CateringItems{get;set;}
public virtual ICollection<BookedCateringItem> CateringItems { get; set; }
CateringItems = new List<CateringItem>();
CateringItems=新列表();
它的类型不同,BookedCateringItem和CateringItem。您需要将其中一个更改为另一个类型。您希望将
列表
分配给ICollection
,因此您不能。如果类型T1和T2相同,您只能将列表
转换为ICollection
。
或者,您可以转换为非通用的i集合
ICollection CateringItems = new List<CateringItem>(); // OK
ICollection CateringItems=new List();//好啊
您正试图将BookedCateringItem的列表分配给CateringItem的集合。类型不匹配-这就是区别BookedCateringItem是什么?尝试新列表(),您需要阅读有关协方差的信息。看,我真蠢!谢谢D@haim770我以为这是关于ICollection和List的兼容性,我太过关注它了,我忽略了我试图初始化的List的类型。Done。对于非泛型ICollection
的额外建议,+1,在某些情况下(WPF视图模型)可能是可取的。