您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

演员表 列出

演员表 列出

您不能 强制转换 (保留参考身份)-这是不安全的。例如:

public interface IFruit {}

public class Apple : IFruit {}
public class Banana : IFruit {}

...

List<Apple> apples = new List<Apple>();
List<IFruit> fruit = apples; // Fortunately not allowed
fruit.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.5
List<IFruit> fruit = apples.Cast<IFruit>().ToList();

但是,这是 一样的铸造原名单-因为现在有两个 单独的 列表。这是安全的,但您需要了解对一个列表所做的更改 不会 在另一列表中显示。(当然,将看到对列表所引用 对象的 修改。)

其他 2022/1/1 18:15:58 有614人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶