如何将一系列项目添加到IList? [英] How to add a range of items to an IList?

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

问题描述

对于 IList< T> ,没有 AddRange()方法.

如何在不迭代项目并使用 Add()方法的情况下将项目列表添加到 IList< T> 中?

How can I add a list of items to an IList<T> without iterating through the items and using the Add() method?

推荐答案

AddRange 是在 List< T> 而不是接口上定义的.

AddRange is defined on List<T>, not the interface.

您可以将变量声明为 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> 可能 not 不是 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 well 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屋!

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