如何将一个类型的通用列表设置为其接口的通用列表?

3
如何将一个类型的通用列表设置为其接口的通用列表?
我有一个从ICar继承的Car类。
我有一个Client类,它在构造函数中接受List对象,我不想明确地为Client类编写List。
但是它不可能设置。
var carsList = new List<Car>();
List<ICar> cars = carsList // compile error
var client = new Client(cars);

你如何实现这个目标?

我发现如果我使用IList,它可以工作,但我需要显式地将我的carsList对象强制转换。


https://dev59.com/xHI-5IYBdhLWcg3wED5V - Joshua Enfield
5个回答

2

您将无法使用.NET Framework List并进行您想要的隐式转换类型。

我会从另一个线程中窃取一些内容来演示根本问题:

考虑:

List<Animal> animals = new List<Giraffe>();
animals.Add(new Monkey());

或使用您的代码:

interface ICar{}
class Car:ICar{}
class BatMobile:ICar{}

List<ICar> cars = new List<Car>()
cars.Add(new BatMobile()) // We can't add a BatMobile to a List of Car. 

由于您可以通过IEnumerable接口确保用户无法通过该接口修改集合,因此IEnumerable与这种类型的变化兼容。 但是,对于列表,无法保证这一点。

https://dev59.com/xHI-5IYBdhLWcg3wED5V#2033931


1

有三种方式存在:

1) define carsList as List<ICar>
2) use framework 4.0 and IEnumerable<ICar>
3) manually convert

1

你不能直接将 List<Car> 强制转换为 List<ICar>,因为你可能会尝试将 OtherCar 添加到你的 List<ICar> 中,而这样做是行不通的。

相反,你可以:

  • 将构造函数参数作为协变接口,例如 IEnumerable<Car>,并在构造函数内部创建一个列表;或者
  • 通过 List<ICar> cars = carsList.ToList<ICar>(); 在构造函数外部转换列表。

0

将列表定义为ICars的列表...

var carsList = new List<ICar>();
List<ICar> cars = carsList; // compile error gone :)

0

你必须反过来做。

var carsList = new List<ICar>(); // Hey, why not?
var client = new Client(cars);

你尝试过强制类型转换吗?

List<ICar> carsList = (List<ICar>)implementationList;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接