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

问题描述:

我有一个基类Base和类A/B从它继承。在C中用OfType过滤一个类型的对象#

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); 
} 

当我编译的代码,我得到这个错误:

error CS0428: Cannot convert method group 'OfType' to non-delegate type 'Base'. Did you intend to invoke the method?

什么问题用代码?

+2

这是一种方法,你忘了括号。 OfType ()。 – 2012-04-15 20:15:31

+0

尝试遍历整个列表,并使用typeof检查每个类型。数组列表让你存储ant类型的对象。 – 2012-04-15 20:17:18

+0

@ user1260028:如果他正确使用该方法,则OP的方法将工作得很好。 *绝对*不需要开始使用非泛型集合(urgh)。 – 2012-04-15 20:21:14

有两个问题:

  • OfType回报IEnumerable<T>,不T
  • 这是一个方法 - 你忘了括号

也许你想:

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

括号?

这是一个函数而不是运算符。

Base f = list.OfType<A>() 

退房参考:

Enumerable.OfType(Of TResult) Method