如何将一系列项添加到IList变量 [英] how to add a range of items to the IList variable

查看:73
本文介绍了如何将一系列项添加到IList变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 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.

一种方法是通过使用作为运算符(自C#7起)。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆