如何将一系列项添加到IList变量 [英] how to add a range of items to the IList variable
问题描述
对于 IList< T>
没有 AddRange()
方法。
如何在不迭代项目和使用 Add()<的情况下将项目列表添加到
IList< T>
/ code>方法?
How can I add a list of items to a IList<T>
without iterating through items and using Add()
method ?
推荐答案
AddRange
在 List<中定义; T>
,而不是接口。
您可以将变量声明为 List< T>
IList< T>
或将其强制转换为 List< T>
,以获取对的访问权限AddRange
。
You can declare the variable as List<T>
instead of IList<T>
or cast it to List<T>
in order to gain access to AddRange
.
((List<myType>)myIList).AddRange(anotherList);
这不是一个好习惯(请参见下面的评论),因为 IList< T>
可能不是 是 List< T>
,但是其他一些实现了接口的类型却可能不会有 AddRange
方法-在这种情况下,您只会找出代码在运行时引发异常。
This is not good practice (see comments below), as an IList<T>
might not be a List<T>
, but some other type that implemented the interface and may very will not have an AddRange
method - in such a case, you will only find out when your code throws an exception at runtime.
因此,除非您知道确定类型确实是 List< T>
,您不应尝试使用 AddRange
。
So, unless you know for certain that the type is indeed a List<T>
you shouldn't try to use AddRange
.
One way to do so is by testing the type with the is or as operators (since C# 7).
if(myIList is List<T>)
{
// can cast and AddRange
}
else
{
// iterate with Add
}
这篇关于如何将一系列项添加到IList变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!