我收到一個我不明白的編譯錯誤。我確信這段代碼應該可以作業,但它沒有編譯。我只是忘記了一些明顯的事情嗎?這是我的代碼和錯誤訊息:
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>();
}
}
我用谷歌搜索過,人們說我應該確保匯入System.Linq,但正如你所見,我已經這樣做了,但我仍然遇到這個問題。我錯過了什么?如果相關,使用 Unity 20121.2.7f1 和 VSCode 時會出現此錯誤。
uj5u.com熱心網友回復:
您正在強制它轉換為B并非所有As 都是Bs 的 a。List<A>沒有實作IEnumerable<B>這就是ToList<T>需要的。
也許你會想要類似的東西All.OfType<B>().ToList()?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/416077.html
標籤:
下一篇:為什么乒乓球在航路點上不起作用?
