<T> 当将列表作为构造函数传递给另一个列表时,为什么要强制转换为 IEnumerable?



我看到了以下代码:

this.list = new List<GameObject>((IEnumerable<GameObject>) this.someVar.otherList);

其中otherList声明如下:

public List<GameObject> otherList = new List<GameObject>();

为什么我们需要将传递给构造函数的列表强制转换为(IEnumerable<GameObject>),这里到底发生了什么?

你永远都不必这么做。构造函数接受IEnumerable<T>,这就是它得到的结果——无论您是显式(new List<GameObject>((IEnumerable<GameObject>)otherList)(还是隐式(new List<GameObject>(otherList)(执行强制转换。

您希望显式的唯一原因是存在多个重载,例如,如果存在占用List<GameObject>的重载,并且出于某种原因您特别希望使用第IEnumerable<GameObject>个重载。

如果生成了代码,那么使用显式强制转换是可以理解的。如果是手写的,需要有人复习他们对C#的了解:(

这不是必须的。我不知道为什么要这样做,但List构造函数接受IEnumerable对象。列表已经IEnumerable对象,因此强制转换是多余的。

最新更新