2012-04-15 52 views
0

我有此代码以获得“A”作为过滤结果。OfType <????>当在C#中使用方法的参数

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

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

+5

你不能调用'Method(list)' - 'list'不是'Base',它是'IEnumerable '。这是你第二次犯这个错误 - 你用IEnumerable ''有多舒服?并且'Method' *总是*意味着返回一个'A'值?如果是这样,为什么它会声明返回'Base',为什么不能使用'A'而不是'''? – 2012-04-15 20:31:18

+0

@Jon:Method()的参数应该是'IEnumerable list,Base b'。对于????,我需要从第二个参数中获得类型A.我尝试使用(Base b)作为参数,并在中使用b.GetType(),但它不起作用,因为b.GetType()返回Type not base。 – prosseek 2012-04-15 20:40:54

回答

4

看起来好像你正在寻找一种通用的方式来做Method什么是基于Base不同的儿童类型。你可以做到这一点:

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

这将从bT类型(必须的Base一个孩子)的返回的第一个实例。

+1

请注意,虽然这被接受,但它不符合实际要求的问题 - 即从参数值中获取类型。这是一个有点混乱的问题,无可否认...... – 2012-04-15 20:48:12

+1

我的原始答案远不如他们所要求的,并且显然是正确的。这是我试图做一些有用的尝试。希望它确实有帮助。 :) – 2012-04-15 20:51:09

+0

@ M.Babcock - 这正是我想要的。谢谢。 – prosseek 2012-04-16 16:19:41

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

如果它不是你要搜索的内容,请澄清。

+0

@ M.Babcock:你的意思是OfType,还是typeof? – 2012-04-15 20:44:37

+1

这不就是'OfType '已经做了什么? – 2012-04-15 20:45:37

+0

@JonSkeet - 编辑(或者转发,因为我没有及时赶上)。 – 2012-04-15 20:46:01