使用ToArray()将列表转换为数组 [英] Converting a list to an array with ToArray()

查看:147
本文介绍了使用ToArray()将列表转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

提前谢谢.

我的错,我编写的第一行代码确实输入错了!

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()

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

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

谢谢大家的回答.

推荐答案

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

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

listItem myList = new List<listItem>();

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

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

替换为

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

创建一个listItem列表.然后

to create a list of listItem. Then

listItem[] myArray = myList.ToArray();

将起作用.

这篇关于使用ToArray()将列表转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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