【问题标题】:C# List to ICollectionC# 列表到 ICollection
【发布时间】: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#


【解决方案1】:

如果类型 T1 和 T2 相同,则只能将 List&lt;T1&gt; 转换为 ICollection&lt;T2&gt;。 或者,您可以转换为非泛型 ICollection

ICollection CateringItems = new List<CateringItem>(); // OK

【讨论】:

  • 完成。对于非通用 ICollection 的额外建议 +1,在某些情况下(WPF 视图模型)可能是可取的。
【解决方案2】:
    public virtual ICollection<BookedCateringItem> CateringItems { get; set; }
    CateringItems = new List<CateringItem>();

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

【讨论】:

    【解决方案3】:

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

    显然它们不兼容......

    【讨论】:

      【解决方案4】:

      你想将List&lt;CateringItem&gt;分配给ICollection&lt;BookedCateringItem&gt;所以你不能。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多