为了账号安全,请及时绑定邮箱和手机立即绑定

从IEnumerable到列表的无效转换

从IEnumerable到列表的无效转换

C#
收到一只叮咚 2021-05-12 17:09:30
我正在Unity3D项目中的C#脚本上工作,在这里尝试获取字符串列表并获取排列的2D列表。以以下方式使用此答案 GetPermutations():List<string> ingredientList = new List<string>(new string[] { "ingredient1", "ingredient2", "ingredient3" });List<List<string>> permutationLists = GetPermutations(ingredientList, ingredientList.Count);但这会引发隐式转换错误:IEnumerable<IEnumerable<string>> to List<List<string>> ... An explicit conversion exists (are you missing a cast)?因此,我查看了一些地方,例如此处,并进行了以下修改:List<List<string>> permutationLists = GetPermutations(ingredientList, ingredientList.Count).Cast<List<string>>().ToList();但是它会在运行时中断,在内部进行处理,并允许其继续运行而不会出现故障-可能是因为它在Unity3D中运行。这是我停止调试脚本后在Unity3D中看到的内容:InvalidCastException: Cannot cast from source type to destination type.System.Linq.Enumerable+<CreateCastIterator>c__Iterator0`1[System.Collections.Generic.List`1[System.String]].MoveNext ()System.Collections.Generic.List`1[System.Collections.Generic.List`1[System.String]].AddEnumerable (IEnumerable`1 enumerable) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/List.cs:128)System.Collections.Generic.List`1[System.Collections.Generic.List`1[System.String]]..ctor (IEnumerable`1 collection) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/List.cs:65)System.Linq.Enumerable.ToList[List`1] (IEnumerable`1 source)我认为这仍然是错误的转换,因此我还尝试了以下方法以及我不记得的更多方法:List<List<string>> permutationLists = GetPermutations(ingredientList, ingredientList.Count).Cast<List<List<string>>>();List<List<string>> permutationLists = GetPermutations(ingredientList.AsEnumerable(), ingredientList.Count);以及像在C或Java中一样,在方法调用之前显式地使用括号进行强制转换,但仍然无济于事。那么,我应该如何从GetPermutations()函数中强制转换结果以获得a List<List<string>>?或者,List<List<string>>由于不需要通用类型的功能,我该如何修改该功能以使其仅返回?我试图将方法修改为以下形式:但是,<T>从函数名称中删除了,它会断言主体不能是迭代器块。我没有使用C#的经验,并且对强类型语言的模板功能不满意,因此不胜感激。我不知道如何查找这个问题,所以如果这是重复的,只需在这里发布,我会立即删除这篇文章。
查看完整描述

2 回答

  • 2 回答
  • 0 关注
  • 201 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信