[英]'List<A>' does not contain a definition for 'ToList'
I'm getting a compiation error that I don't understand.我收到一个我不明白的编译错误。 I am convinced that this code should work but it is not compiling.我确信这段代码应该可以工作,但它没有编译。 Am I just forgetting something obvious?我只是忘记了一些明显的事情吗? This is my code and the error message:这是我的代码和错误消息:
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>();
}
}
I have Googled and people say I should make sure to import System.Linq
but, as you can see, I've already done that, and I'm still having this problem.我用谷歌搜索过,人们说我应该确保导入System.Linq
但是,正如你所看到的,我已经这样做了,但我仍然遇到这个问题。 What am I missing?我错过了什么? If relevant, this error is seen while using Unity 20121.2.7f1 and VSCode.如果相关,使用 Unity 20121.2.7f1 和 VSCode 时会出现此错误。
You are forcing it to convert to a B
which not all A
s are B
s.您正在强迫它转换为并非所有A
都是B
的B
List<A>
doesn't implement IEnumerable<B>
which thats what ToList<T>
requires. List<A>
没有实现ToList<T>
需要的IEnumerable<B>
。
Perhaps you would want something like All.OfType<B>().ToList()
?也许您想要All.OfType<B>().ToList()
类的东西?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.