简体   繁体   English

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

[英]Filtering the object of a type with OfType in C#

I have a base class Base, and class A/B that inherits from it. 我有一个基类Base,以及继承它的A / B类。

public class Base
{
    int x;
}
public class A : Base
{
    int y;
}
public class B : Base
{
    int z;
}

I tried to use OfType to filter the only object that I need as follows: 我尝试使用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);
}

When I compiled the code, I got this error: 当我编译代码时,我收到此错误:

error CS0428: Cannot convert method group 'OfType' to non-delegate type 'Base'. 错误CS0428:无法将方法组'OfType'转换为非委托类型'Base'。 Did you intend to invoke the method? 你打算调用这个方法吗?

What's wrong with the code? 代码有什么问题?

There are two problems: 有两个问题:

  • OfType returns IEnumerable<T> , not T OfType返回IEnumerable<T> ,而不是T
  • It's a method - you forgot the brackets 这是一种方法 - 你忘了括号

Perhaps you wanted: 也许你想要:

Base f = list.OfType<A>().FirstOrDefault();

?

Brackets ? 括号?

This is a function and not operator. 这是一个功能而不是操作员。

Base f = list.OfType<A>()

Check out the reference: 查看参考:

Enumerable.OfType(Of TResult) Method Enumerable.OfType(Of TResult)方法

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

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