[英]How can I convert a generic List<T> to a List?
How can I convert a generic List to a List? 如何将通用列表转换为列表?
I am using a ListCollectionView
and I need to provide it with an IList
not an IList<T>
. 我正在使用ListCollectionView
,我需要为它提供一个IList
而不是IList<T>
。
I see plenty of examples to convert an IList
to a IList<T>
, but not the other way. 我看到很多例子可以将IList
转换为IList<T>
,但不是另一种方式。
Do I just convert it manually ( new List().AddRange(IList<T>
)? 我只是手动转换它( new List().AddRange(IList<T>
)?
To clarify the other answers: 澄清其他答案:
IList<T>
does not require an implementing type to also implement IList
. IList<T>
不需要实施类型也实现IList
。 IEnumerable<T>
does require IEnumerable
. IEnumerable<T>
确实需要IEnumerable
。 We can get away with that with IEnumerable<T>
because a sequence of T can always be treated as a sequence of objects. 我们可以通过IEnumerable<T>
来解决这个问题,因为IEnumerable<T>
的序列总是可以被视为一系列对象。 But a list of giraffes cannot be treated as a list of objects; 但是长颈鹿的名单不能被视为对象列表; you can add a tiger to a list of objects. 您可以将老虎添加到对象列表中。
However, List<T>
does unsafely implement IList
. 但是, List<T>
会不安全地实现IList
。 If you try to add a tiger to a List<Giraffe>
by first casting it to IList, you'll get an exception. 如果您尝试将老虎添加到List<Giraffe>
,首先将其投射到IList,您将获得异常。
So to answer the question: If all you have in hand is an IList<T>
, you can speculatively cast it to IList
with the "as" operator, and if that fails, then create a new ArrayList
or List<object>
and copy the contents in. If what you have in hand is a List<T>
then you already have something that implements IList
directly. 所以回答这个问题:如果您拥有的只是一个IList<T>
,您可以推测性地使用“as”运算符将其IList
为IList
,如果失败,则创建一个新的ArrayList
或List<object>
并复制如果您拥有的是List<T>
那么您已经拥有了直接实现IList
东西。
As List<T>
implements the IList
interface, you can simply provide the List<T>
. 由于List<T>
实现IList
接口,您只需提供List<T>
。 If needed, just cast it: 如果需要,只需投下它:
List<int> list = new List<int>();
IList ilist = (IList)list;
You don't have to do any conversion at all. 您根本不需要进行任何转换。 A List<T>
implements the IList
interface. List<T>
实现IList
接口。
If you need the type IList
for example to use a specific overload, just use the cast syntax (IList)theList
. 如果您需要类型IList
例如使用特定的重载,只需使用(IList)theList
语法(IList)theList
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.