C# 使用 ToArray() 将列表转换为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9990378/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:01:27  来源:igfitidea点击:

Converting a list to an array with ToArray()

c#listerror-handlingtype-conversiontoarray

提问by Jodll

I've created a class called listItem and the following list:

我创建了一个名为 listItem 的类和以下列表:

List<listItem> myList = new List<listItem>();

At some point in my code, I want to convert it to an array, thereby using:

在我的代码中的某个时刻,我想将其转换为数组,从而使用:

listItem[] myArray = myList.ToArray();

Unfortunately, this doesn't work, and I get this error message:

不幸的是,这不起作用,我收到此错误消息:

Cannot convert [...] listItem[] to [...] List<listItem>

I tried to figure this out, but very unsuccessfully...

我试图弄清楚这一点,但非常不成功......

Thanks in advance.

提前致谢。

EDIT: My bad, the first code line I wrote was indeed mistyped!

编辑:我的错,我写的第一行代码确实打错了!

Actually, all the code above works pretty well. My error was due to the fact that my function:

实际上,上面的所有代码都运行得很好。我的错误是由于我的函数:

List<listItem> myFunction()

returned myArray, hence the conversion problem... It is now fixed. :)

返回 myArray,因此转换问题...现在已修复。:)

Thank you all for your answers.

谢谢大家的答案。

采纳答案by Gabber

This is the error (as pointed out from Darkshadw and Jon Skeet)

这是错误(正如 Darkshadw 和 Jon Skeet 指出的那样)

listItem myList = new List<listItem>();

You are assigning the value of a List to a listItem.

您正在将 List 的值分配给 listItem。

Replace it with

将其替换为

List<listItem> myList = new List<listItem>();

to create a list of listItem. Then

创建一个 listItem 列表。然后

listItem[] myArray = myList.ToArray();

will work.

将工作。

回答by Jodll

have you tried

你有没有尝试过

listItem[] myArray = myList.ToArray(new listItem[]{});

in Java it works, im not sure in c#

在 Java 中它有效,我不确定在 C# 中

回答by R.D.

string[] s = myList.ToArray();

Considering myList is list of string

考虑到 myList 是字符串列表