错误:“无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“System.Collections.Generic.List

16 浏览
0 Comments

错误:“无法将类型“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()
    {
        List listBuffer = 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]);
    }
}

0
0 Comments

这是一个类型转换错误,错误提示为"Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.List'"。错误的原因是在声明变量listInt2时,将一个IEnumerable类型的对象赋值给了List类型的变量,而这两个类型之间无法直接进行隐式转换。

解决方法是使用ToList()方法将IEnumerable类型的对象转换为List类型。修改后的代码如下:

List listInt2 = stringBuffer
    .Split(',')
    .Select(c => Int32.Parse(c, CultureInfo.InvariantCulture)).ToList();

通过调用ToList()方法,将Select()方法返回的IEnumerable类型的集合转换为List类型的集合,从而解决了类型转换错误。

这个问题发生的原因可能是编写者在声明变量时忽略了类型转换的问题,导致错误的赋值操作。感谢作者及时发现错误并修正。

0