Unity3D中C#脚本IEnumerable转List无效转换问题求助
解决Unity C#中排列结果的类型转换错误
嘿,咱们来搞定你在Unity脚本里遇到的这个类型不匹配问题!你现在的核心问题是GetPermutations返回的是IEnumerable<IEnumerable<string>>,但你想直接把它赋值给List<List<string>>——C#没法自动把嵌套的IEnumerable转换成List,因为这俩是不同的集合类型,得手动处理两层转换才行。
具体解决步骤:
先搞懂类型差异:
外层的IEnumerable可以用.ToList()转成List,但里面每个IEnumerable<string>也得单独转成List<string>,所以得做两层转换,不能一步到位。修改你的调用代码:
把原来的赋值语句改成下面这样,用LINQ的Select先把每个内部的排列集合转成List<string>,再把整个外层集合转成List<List<string>>:List<string> ingredientList = new List<string>(new string[] { "ingredient1", "ingredient2", "ingredient3" }); // 先转换内部集合,再转换外层集合 List<List<string>> permutationLists = GetPermutations(ingredientList, ingredientList.Count) .Select(perm => perm.ToList()) .ToList();别忘了在脚本顶部加上
using System.Linq;,不然Select和ToList()这些LINQ方法会找不到哦!确认GetPermutations的返回类型:
确保你的GetPermutations方法返回的是IEnumerable<IEnumerable<T>>,这里给你一个常见的实现示例,方便你对照检查:public static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> items, int length) { if (length == 1) return items.Select(item => new T[] { item }); return GetPermutations(items, length - 1) .SelectMany(perm => items.Where(item => !perm.Contains(item)), (existingPerm, newItem) => existingPerm.Concat(new T[] { newItem })); }
为啥原来的代码会报错?
- Invalid cast from IEnumerable to List:如果你之前尝试过强制转换(比如
(List<List<string>>)GetPermutations(...)),那肯定会失败——IEnumerable不是List的子类,这种强转根本不合法。 - 隐式转换错误:C#不会自动帮你把
IEnumerable<IEnumerable<string>>转成List<List<string>>,因为这需要把每个内部集合都显式转换成List,必须手动写代码处理。
内容的提问来源于stack exchange,提问作者Darrel Holt
相关产品推荐
相关产品推荐

