【发布时间】:2012-04-15 20:28:52
【问题描述】:
我有这段代码来获得“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);
}
我在 '????' 中使用什么参数从原始代码中获得相同的结果?
【问题讨论】:
-
你不能打电话给
Method(list)-list不是Base,而是IEnumerable<Base>。这是你第二次犯这个错误——你对IEnumerable<T>感觉如何?Method总是 是否意味着返回A值?如果是这样,为什么声明返回Base,为什么不能只使用A而不是????? -
@Jon: Method() 的参数应该是
IEnumerable<Base> list, Base b。对于??????,我需要从第二个参数中获取类型 A。我尝试使用 (Base b) 作为参数,并在 ???> 中使用 b.GetType(),但它不起作用,因为 b.GetType() 返回 Type 而不是 Base。