错误:“无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“System.Collections.Generic.List”
错误:“无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“System.Collections.Generic.List”
我试图将一个数字列表转换成字符串,然后再转回列表。转换成字符串没有问题,但当我将其转回列表时,出现了错误“无法隐式转换类型'System.Collections.Generic.IEnumerable'。这是我运行的代码。
using System; using System.Collections.Generic; using UnityEngine; using System.Linq; using System.Globalization; public class Test : MonoBehaviour { void Start() { Function(); } void Function() { ListlistBuffer = new List (); System.Random rnd = new System.Random(); for (int x = 1; x < 100; x++) { listBuffer.Add(x); } List listInt = (from item in listBuffer orderby rnd.Next() select item).ToList (); print(listInt[0]); string stringBuffer = String.Join(", ", listInt.Select(n => n.ToString(CultureInfo.InvariantCulture)).ToArray()); print(stringBuffer); List listInt2 = stringBuffer.Split(',').Select(c => Int32.Parse(c, CultureInfo.InvariantCulture)).ToList(); print(listInt2[0]); } }
这是一个类型转换错误,错误提示为"Cannot implicitly convert type 'System.Collections.Generic.IEnumerable
解决方法是使用ToList()方法将IEnumerable
ListlistInt2 = stringBuffer .Split(',') .Select(c => Int32.Parse(c, CultureInfo.InvariantCulture)).ToList();
通过调用ToList()方法,将Select()方法返回的IEnumerable
这个问题发生的原因可能是编写者在声明变量时忽略了类型转换的问题,导致错误的赋值操作。感谢作者及时发现错误并修正。