在C#中使用OfType过滤类型的对象 [英] Filtering the object of a type with OfType in C#
本文介绍了在C#中使用OfType过滤类型的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个基类Base和一个继承自它的类A/B.
I have a base class Base, and class A/B that inherits from it.
public class Base
{
int x;
}
public class A : Base
{
int y;
}
public class B : Base
{
int z;
}
我试图使用OfType过滤我唯一需要的对象,如下所示:
I tried to use OfType to filter the only object that I need as follows:
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);
}
编译代码时,出现此错误:
When I compiled the code, I got this error:
错误CS0428:无法将方法组'OfType'转换为非委托类型'Base'.你打算吗 调用该方法?
error CS0428: Cannot convert method group 'OfType' to non-delegate type 'Base'. Did you intend to invoke the method?
代码有什么问题?
推荐答案
有两个问题:
-
OfType
返回IEnumerable<T>
,而不是T
- 这是一种方法-您忘记了括号
OfType
returnsIEnumerable<T>
, notT
- It's a method - you forgot the brackets
也许您想要:
Base f = list.OfType<A>().FirstOrDefault();
?
这篇关于在C#中使用OfType过滤类型的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文