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/