0

我有这个代码来获得“A”作为过滤结果。

public static void RunSnippet()
{
    Base xbase = new Base(); 
    A a = new A(); 
    B b = new B();
    IEnumerable<Base> list = new List<Base>() { xbase, a, b };
    Base f = list.OfType<A>().FirstOrDefault();
    Console.WriteLine(f);
}

我需要使用IEnumerable<Base> list = new List<Base>() {xbase, a, b};如下函数:

public static Base Method(IEnumerable<Base> list, Base b (????)) // I'm not sure I need Base b parameter for this?
{
    Base f = list.OfType<????>().FirstOrDefault();
    return f;
}

public static void RunSnippet()
{
    Base xbase = new Base(); 
    A a = new A(); 
    B b = new B();
    IEnumerable<Base> list = new List<Base>() { xbase, a, b };
    //Base f = list.OfType<A>().FirstOrDefault();
    Base f = Method(list);
    Console.WriteLine(f);
}

我在'????'中使用什么参数 从原始代码中获得相同的结果?

4

2 回答 2

5

似乎您正在寻找一种通用的方法来Method根据不同的子类型来执行Base. 你可以这样做:

public static Base Method<T>(IEnumerable<Base> b) where T: Base
{
    Base f = list.OfType<T>().FirstOrDefault();
    return f;
}

这将返回第一个b类型的实例T(它必须是 的子级Base)。

于 2012-04-15T20:39:20.460 回答
2

如果你想查询一个类型,你可以尝试这样的事情:

public static Base Method(IEnumerable<Base> list, Type typeToFind)
{
   Base f =  (from l in list  
       where l.GetType()== typeToFind 
               select l).FirstOrDefault();
   return f;
}

如果这不是您要搜索的内容,请澄清。

于 2012-04-15T20:39:28.900 回答