繁体   English   中英

在C#中使用OfType过滤类型的对象

[英]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();

括号?

这是一个功能而不是操作员。

Base f = list.OfType<A>()

查看参考:

Enumerable.OfType(Of TResult)方法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM