在C#中将IList转换为数组 [英] Convert IList to array in C#
问题描述
我想将IList转换为数组: 请查看我的代码:
I want to convert IList to array: Please see my code:
IList list = new ArrayList();
list.Add(1);
Array array = new Array[list.Count];
list.CopyTo(array, 0);
为什么会出现 System.InvalidCastException:无法将源数组中的至少一个元素转换为目标数组类型?假设我不能使用 ArrayList 作为 list 变量的类型,如何解决?
Why I get System.InvalidCastException : At least one element in the source array could not be cast down to the destination array type? How that can be resolved assuming I can not use ArrayList as type for list variable ?
更新1:我使用.NET 1.1.所以我不能使用Generics,Linq等.我只是想接收最常见情况的结果-以整数为例,我需要此代码适用于所有类型,因此我在这里使用 Array (也许我错用了Array,但我需要,再次,是常见情况).
Update 1: I use .NET 1.1. So I can not use Generics, Linq and so on. I just want to receive result for the most common case - integer was given as example, I need this code works for all types so I use Array here (maybe I am wrong about using Array but I need, once again, common case).
推荐答案
您正在创建由Array
个值组成的数组 . 1是int
,而不是Array
.您应该具有:
You're creating an array of Array
values. 1 is an int
, not an Array
. You should have:
IList list = new ArrayList();
list.Add(1);
Array array = new int[list.Count];
list.CopyTo(array, 0);
或者,理想情况下,请勿使用非泛型类型开始...使用列表而不是ArrayList
,IList<T>
而不是IList
等.
or, ideally, don't use the non-generic types to start with... use List instead of ArrayList
, IList<T>
instead of IList
etc.
请注意,第三行可能很容易:
Note that the third line could easily be:
Array array = new object[list.Count];
相反.
这篇关于在C#中将IList转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!