您不能 强制转换 (保留参考身份)-这是不安全的。例如:
public interface IFruit {}public class Apple : IFruit {}public class Banana : IFruit {}...List<Apple> apples = new List<Apple>();List<IFruit> fruit = apples; // Fortunately not allowedfruit.Add(new Banana());// Eek - it's a banana!Apple apple = apples[0];现在你可以转换
List<Apple>成
IEnumerable<IFruit>在.NET 4 /
C#4,由于协方差,但如果你想有一个
List<IFruit>你必须建立一个 新的 列表。例如:
// In .NET 4, using the covariance of IEnumerable<T>List<IFruit> fruit = apples.ToList<IFruit>();// In .NET 3.5List<IFruit> fruit = apples.Cast<IFruit>().ToList();
但是,这是 不 一样的铸造原名单-因为现在有两个 单独的 列表。这是安全的,但您需要了解对一个列表所做的更改 不会
在另一列表中显示。(当然,将看到对列表所引用 对象的 修改。)



