c# - 将 List<T> 转换为 List<Interface>

标签 c# .net interface casting

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

}

我怎么投 List<Client>List<IDic>

最佳答案

你不能转换它(保留引用身份)——那是不安全的。例如:

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

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

关于c# - 将 List<T> 转换为 List<Interface>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8925400/

相关文章:

c# - 使用依赖注入(inject)时避免单例存储库(DryIoc)

asp.net - 如何从 HttpResponseMessage 获取对象?

c# - 类型参数约束是一个类

c# winforms - 在模式窗体之间传递参数

c# - 在 wpf 窗口中添加大量文本框的最佳方法是什么

c# - 进度条直到100%才更新

.Net 内存限制

.net - 在 Wcf REST 中,是返回请求较少的较大模型更好,还是返回请求较多的较小模型更好

java - Iterable<Key> 作为返回类型,这是什么意思?

java - 在 Java 中建模数字类型和它们之间的算术运算