【发布时间】: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<Library.Product> 隐式转换为System.Collections.Generic.List<Library.IHierarchicalEntity>
Manufacturer 和 Product 都是 IHierarchicalEntity 类型。为什么不把List<Product> 当作List<IHierarchicalEntity> 呢?
【问题讨论】:
-
没有其他说明不能转换成什么类型的列表吗?编译器错误是否从字面上说“......将'System.Collections.Generic.List'输入到'System.Collections.Generic.List'”?
-
我们每天都会在 StackOverflow 上收到这个问题。查看页面右侧链接列表中数百个“相关”问题中的任何一个。
-
搜索“通用方差”可以找到很多类似的问题和答案。 (我现在没有时间这样做。)
-
简短的回答:苹果列表不是水果列表。为什么?因为你可以把一个香蕉放到一个水果列表中,但是你不能把一个香蕉放到一个苹果列表中,所以它们不是同一种类型。
标签: c#