[英]Filtering the object of a type with OfType in C#
我有一個基類Base,以及繼承它的A / B類。
public class Base
{
int x;
}
public class A : Base
{
int y;
}
public class B : Base
{
int z;
}
我嘗試使用OfType來過濾我需要的唯一對象,如下所示:
public static void RunSnippet()
{
Base xbase; A a; B b;
IEnumerable<Base> list = new List<Base>() {xbase, a, b};
Base f = list.OfType<A>; // I need to get only the object A
Console.WriteLine(f);
}
當我編譯代碼時,我收到此錯誤:
錯誤CS0428:無法將方法組'OfType'轉換為非委托類型'Base'。 你打算調用這個方法嗎?
代碼有什么問題?
有兩個問題:
OfType
返回IEnumerable<T>
,而不是T
也許你想要:
Base f = list.OfType<A>().FirstOrDefault();
?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.