【问题标题】:Cannot implicitly convert type 'System.Collections.Generic.List<Library.Product>' to 'System.Collections.Generic.List<Library.IHierarchicalEntity>' [duplicate]无法将类型“System.Collections.Generic.List<Library.Product>”隐式转换为“System.Collections.Generic.List<Library.IHierarchicalEntity>”[重复]
【发布时间】:2011-10-05 15:45:28
【问题描述】:

可能重复:
In C#, why can't a List<string> object be stored in a List<object> variable

我有以下代码。

   public class Manufacturer :  IHierarchicalEntity
    {
        public string ManufacturerName
        {
            get
            {
                return _manfuacturerName;
            }
            set
            {
                _manfuacturerName = value;
            }
        } private string _manfuacturerName;

        public List<Product> Products
        {
            get
            {
                return _products;
            }
        } private List<Product> _products;

        #region IHierarchicalEntity Members

        public List<IHierarchicalEntity> Children
        {
            get
            {
                return Products; //This is where I get the compiler error
            }
        }

        #endregion
    }

    public class Product :  IHierarchicalEntity{}

    public interface IHierarchicalEntity
    {
        List<IHierarchicalEntity> Children { get; }
    }

我得到一个编译器异常

无法将类型System.Collections.Generic.List&lt;Library.Product&gt; 隐式转换为System.Collections.Generic.List&lt;Library.IHierarchicalEntity&gt;

Manufacturer 和 Product 都是 IHierarchicalEntity 类型。为什么不把List&lt;Product&gt; 当作List&lt;IHierarchicalEntity&gt; 呢?

【问题讨论】:

  • 没有其他说明不能转换成什么类型​​的列表吗?编译器错误是否从字面上说“......将'System.Collections.Generic.List'输入到'System.Collections.Generic.List'”?
  • 我们每天都会在 StackOverflow 上收到这个问题。查看页面右侧链接列表中数百个“相关”问题中的任何一个。
  • 搜索“通用方差”可以找到很多类似的问题和答案。 (我现在没有时间这样做。)
  • 简短的回答:苹果列表不是水果列表。为什么?因为你可以把一个香蕉放到一个水果列表中,但是你不能把一个香蕉放到一个苹果列表中,所以它们不是同一种类型。

标签: c#


【解决方案1】:

这种转换是不可能的,否则您可以将OtherHierarchicalEntity 添加到List&lt;Product&gt;,因此它不安全。您可以显式转换并返回一个新列表:

  return Products.Cast<IHierarchicalEntity>().ToList();

【讨论】:

    【解决方案2】:

    尝试做:

    return Products.ToList<IHierarchicalEntity>();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-02
      相关资源
      最近更新 更多