简体   繁体   English

OfType参数 <????> 在C#方法中使用时

[英]Parameter of OfType<????> when used in a method with C#

I have this code to get "A" as a filtered result. 我有此代码来获取“ 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);
}

I need to use IEnumerable<Base> list = new List<Base>() {xbase, a, b}; 我需要使用IEnumerable<Base> list = new List<Base>() {xbase, a, b}; from a function as follows: 从如下函数:

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

What parameter do I use in '????' 我在'????'中使用什么参数 to get the same result from the original code? 从原始代码中获得相同的结果?

It seems like you are looking for a generic way to do what is in Method based on different children types of Base . 似乎您正在寻找一种通用方法来根据不同的Base子类型执行Method的操作。 You can do that with: 您可以执行以下操作:

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

This will return the first instance from b that is of type T (which has to be a child of Base ). 这将从b中返回类型为T的第一个实例(必须是Base的子实例)。

If you want to query on a type, you can try something like this: 如果要查询类型,可以尝试如下操作:

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

If it's not what you are searching for, please clarify. 如果不是您要搜索的内容,请进行澄清。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM