无法将List强制转换为IList

时间:2014-11-20 10:05:37

标签: c# casting

我正在尝试将List转换为IList,但无法投射。编译器允许我将它仅转换为IEnumerable:

//Not allowed, why?
public override IList<ILineEntity> Lines
{
   get { return _PharamaLines ?? (_PharamaLines = new List<PharamaLine>()); }
}

//Allowed
public override IEnumerable<ILineEntity> Lines
{
   get { return _PharamaLines ?? (_PharamaLines = new List<PharamaLine>()); }
}

PharamaLine的类型为ILineEntity

  

错误:无法将类型“System.Collections.Generic.List<FW.PharamaLine>”隐式转换为“System.Collections.Generic.IList<Foundation.Interfaces.ILineEntity>”。存在显式转换(您是否错过了演员?)

1 个答案:

答案 0 :(得分:8)

原因是:

IList<T> 不变,而IEnumerable<out T>协变out关键字)。

如果您定义List<PharamaLine>,则基本上声明您只能将PharmaLine个对象添加到列表中,但您可以添加不同的 ILineEntity个对象一个IList<ILineEntity>,这将破坏合同。

假设您有一些课程OtherLine : ILineEntity。想象一下这段代码是有效的:

var list = new List<PharmaLine>();
var list2 = (IList<ILineEntity>)list; // Invalid!
list2.Add(new OtherLine()); // This should work if the cast were valid

这适用于可枚举的,因为PharmaLine的序列总是 ILineEntity的有效序列(协方差)。

请注意,您也可以使用IReadOnlyList<out T>,它也是协变的,但缺少允许您修改列表的方法。