Gla*_*eep 0 c# unity-game-engine
我收到一个我不明白的编译错误。我确信这段代码应该可以工作,但无法编译。我只是忘记了一些明显的事情吗?这是我的代码和错误消息:
using System.Collections.Generic;
using System.Linq;
public class A { }
public class B : A { }
public class C : A { }
public static class Foo
{
public static List<A> All = new List<A>
{
new A(),
new B(),
new C()
};
public static List<B> Bs()
{
/*
The error is given here:
(field) static List<A> Foo.All
'List<A>' does not contain a definition for 'ToList' and
the best extension method overload 'Enumerable.ToList<B>(IEnumerable<B>)'
requires a receiver of type 'IEnumerable<B>'
*/
return All.ToList<B>();
}
}
Run Code Online (Sandbox Code Playgroud)
我用谷歌搜索过,人们说我应该确保导入System.Linq,但是,正如你所看到的,我已经这样做了,但我仍然遇到这个问题。我缺少什么?如果相关,则在使用 Unity 20121.2.7f1 和 VSCode 时会出现此错误。
您正在强制它转换为B并非所有As 都是Bs 的 a 。List<A>没有实现IEnumerable<B>这就是所ToList<T>需要的。
也许你想要类似的东西All.OfType<B>().ToList()?