演员表&lt;T&gt;到列表<接口> [英] Cast List&lt;T&gt; to List&lt;Interface&gt;

查看:28
本文介绍了演员表&lt;T&gt;到列表<接口>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public interface IDic
{
    int Id { get; set; }
    string Name { get; set; }
}
public class Client : IDic
{

}

如何将 List 转换为 List?

推荐答案

你不能强制转换(保留引用标识)——那是不安全的.例如:

You can't cast it (preserving reference identity) - that would be unsafe. For example:

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];

现在,由于协方差,您可以在 .NET 4/C# 4 中将 List 转换为 IEnumerable,但是如果您想要 List 您必须创建一个列表.例如:

Now you can convert a List<Apple> to an IEnumerable<IFruit> in .NET 4 / C# 4 due to covariance, but if you want a List<IFruit> you'd have to create a new list. For example:

// 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();

但这与转换原始列表不同 - 因为现在有两个单独的列表.这是安全的,但您需要了解对一个列表所做的更改不会在另一个列表中看到.(当然,会看到对列表所引用的对象的修改.)

But this is not the same as casting the original list - because now there are two separate lists. This is safe, but you need to understand that changes made to one list won't be seen in the other list. (Modifications to the objects that the lists refer to will be seen, of course.)

这篇关于演员表&lt;T&gt;到列表<接口>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆