在 C# 中将 IList 转换为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9507002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert IList to array in C#
提问by Michael Z
I want to convert IList to array: Please see my code:
我想将 IList 转换为数组:请看我的代码:
IList list = new ArrayList();
list.Add(1);
Array array = new Array[list.Count];
list.CopyTo(array, 0);
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 ArrayListas type for listvariable ?
为什么我得到System.InvalidCastException:源数组中的至少一个元素无法转换为目标数组类型?假设我不能使用ArrayList作为列表变量的类型,如何解决这个问题?
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 Arrayhere (maybe I am wrong about using Array but I need, once again, common case).
更新 1:我使用 .NET 1.1。所以我不能使用泛型、Linq 等。我只想接收最常见情况的结果 - 以整数为例,我需要此代码适用于所有类型,所以我在这里使用Array(也许我使用 Array 是错误的,但我再次需要常见情况)。
采纳答案by Jon Skeet
You're creating an array of Arrayvalues. 1 is an int, not an Array. You should have:
你创建一个数组的Array值。1 是int,不是Array。你应该有:
IList list = new ArrayList();
list.Add(1);
Array array = new int[list.Count];
list.CopyTo(array, 0);
or, ideally, don't use the non-generic types to start with... use List instead of ArrayList, IList<T>instead of IListetc.
或者,理想情况下,不要使用非泛型类型开始...使用 List 而不是ArrayList,IList<T>而不是IList等。
EDIT: Note that the third line could easily be:
编辑:请注意,第三行很容易是:
Array array = new object[list.Count];
instead.
反而。
回答by Henk Holterman
I'm surprised that
我很惊讶
Array array = new Array[list.Count];
even compiles but it does not do what you want it to. Use
甚至编译,但它没有做你想要的。用
object[] array = new object[list.Count];
And, standard remark: if you can use C#3 or later, avoid ArrayList as much as possible. You'll probably be happier with a List<int>
并且,标准备注:如果您可以使用 C#3 或更高版本,请尽可能避免使用 ArrayList。你可能会更开心List<int>
回答by Joe
You can use Cast and ToArray:
您可以使用 Cast 和 ToArray:
Array array = list.Cast<int>().ToArray();
回答by Martin Booka Weser
probably the most compact solution is this:
可能最紧凑的解决方案是这样的:
Enumerable.Range(0, list.Count).Select(i => list[i]).ToArray();
Enumerable.Range(0, list.Count).Select(i => list[i]).ToArray();

