小编典典

演员表 列出

c#

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

}

我怎样才能投List<Client>List<IDic>


阅读 303

收藏
2020-05-19

共1个答案

小编典典

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

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

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

2020-05-19