【发布时间】:2018-05-04 21:23:38
【问题描述】:
我正在 Unity3D 项目中处理 C# 脚本,我正在尝试获取字符串列表并获取排列的 2D 列表。以下列方式使用this answer'sGetPermutations():
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)?
于是看了几个地方,比如here,想出如下修改:
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() 函数的结果转换为List<List<string>>?或者,我如何修改函数以仅返回 List<List<string>>,因为我不需要它为泛型类型工作?我尝试自己修改方法如下:
List<List<string>> GetPermutations(List<string> items, int count)
{
int i = 0;
foreach(var item in items)
{
if(count == 1)
yield return new string[] { item };
else
{
foreach(var result in GetPermutations(items.Skip(i + 1), count - 1))
yield return new string[] { item }.Concat(result);
}
++i;
}
}
但是,从函数名中删除 <T> 后,它会中断,说明主体不能是迭代器块。我之前没有使用 C# 的经验,而且我对强类型语言中的模板函数很生疏,因此感谢任何解释/帮助。
我不知道如何查找此问题,所以如果这是重复的,请在此处发布,我会立即删除此帖子。
【问题讨论】:
-
你需要像
GetPermutations(...).Select(c => c.ToList()).ToList()这样的东西
标签: c# casting type-conversion