【问题标题】:Parameter of OfType<????> when used in a method with C#在 C# 方法中使用 OfType<????> 的参数
【发布时间】: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&lt;Base&gt; list = new List&lt;Base&gt;() {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&lt;Base&gt;。这是你第二次犯这个错误——你对IEnumerable&lt;T&gt; 感觉如何? Method 总是 是否意味着返回 A 值?如果是这样,为什么声明返回Base,为什么不能只使用A 而不是????
  • @Jon: Method() 的参数应该是IEnumerable&lt;Base&gt; list, Base b。对于??????,我需要从第二个参数中获取类型 A。我尝试使用 (Base b) 作为参数,并在 ???> 中使用 b.GetType(),但它不起作用,因为 b.GetType() 返回 Type 而不是 Base。

标签: c# linq oftype


【解决方案1】:

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

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

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

【讨论】:

  • 请注意,尽管这已被接受,但它不符合问题实际要求的内容 - 即从参数值中获取类型。诚然,这是一个有点困惑的问题......
  • 我原来的答案远不如他们所问的确定,而且显然是正确的。这是我尝试做一些有用的事情。希望它真的有帮助。 :)
  • @M.Babcock - 这正是我想要的。谢谢。
【解决方案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;
}

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

【讨论】:

  • @M.Babcock:你是说 OfType 还是 typeof?
  • @JonSkeet - 已编辑(或者更确切地说是因为我没有及时看到而重新发布)。
  • @M.Babcock:好的——在这种情况下,我可以回答说不,它们实际上对于子类型是不同的;对于 OfType 你必须在编译时知道 T 。你不能使用OfType&lt;typeToFind&gt;
  • @JonSkeet - 感谢您的澄清。我不知道我自己是否曾在实践中使用过它。这实际上使它没有我想象的那么有用。
  • 如果list包含null,GetType会抛出异常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-13
相关资源
最近更新 更多