如何使用泛型方法构建相同类型的列表?

问题描述:

考虑:如何使用泛型方法构建相同类型的列表?

public static void GetAllTypesInContainer<t>(AContainerWithChildren bw) 
{ 
    var list = new List<t>();  
    var stuff = bw.GetChildren(); 

    foreach (var child in stuff) 
    { 
     if (child.GetType().Name == typeOf(t).Name) 
     { 
      list.Add((t)child); 
     } 
    } 
} 

如何添加该类型的值列表?

+2

你意识到这个方法实际上并没有任何东西,对吧?它创建一个列表并将其抛弃。 – 2015-02-05 22:08:40

+1

'theType'应该是'Type'还是某种类型的实例? – 2015-02-05 22:09:16

+0

是的方法不会做任何事情,因为我还没有决定如何返回列表。我可以迭代变量的东西,如上所示。我不能做的是添加任何东西到列表中,如上所示。类型不是某种东西的实例,而是某种东西。该方法是让我告诉它哪些类型的孩子返回列表中... – 2015-02-05 22:14:57

最终的溶液为:

 public static Container GetAllTypesInContainer<t>(this Container bw, Action<List<t>> Callback) 
    { 
     var list = new List<t>();    
     list= bw.GetChildren().OfType<t>().ToList(); 
     Callback(list); 
     return bw; 
    } 

的原因回调是在流体界面的类型的容器的设计。回调允许我回到静态方法实例类型,而不是名单,因此我可以链中的所有活动,还是处理类似这样的内容:

bw 
    .StoreInformation() 
    .GetAllHtmlHyperLinks((p) => 
    { 
     p.ForEach((q) => 
     { 
      if (q.Href == "Something") 
      { 
      } 
     }); 
    }) 
    .AssertControlTitleOnHomePage(); 

的回调允许我使用匿名方法来处理结果。

如果我理解了代码,您试图让t型的所有孩子进入列表,并忽略其余部分。 Linq使这很容易。我假设调用bw.GetChildren()的结果可以根据您的示例进行枚举。

using System.Linq; 
// ... 

private static List<T> GetAllTypesInContainer<T>(this Container bw) 
{ 
    var list = bw.GetChildren().OfType<T>().ToList(); 
    return list; 
} 

或者优化,以适应流畅的编码风格的OP是后一个版本,保持与容器的背景:

private static Container ForEachChildOfType<T>(this Container bw, Action<T> action) 
{ 
    var children = bw.GetChildren().OfType<T>().ToList(); 

    children.Do(action); 

    return bw; 
} 

// later to be used similar as follows as per OP's example 

bw 
    .StoreInformation() 
    .ForEachChildOfType<HtmlHyperLink>(link => 
    { 
     if (link.Href == "Something") // caution, watch for mixed case!!! 
     { 
     } 
    }) 
    .AssertControlTitleOnHomePage(); 

NB作为一般的编码风格我从来没有调用方法GetXXX除非它真的返回了一些东西,所以名字改变了。

ps。希望这里没有错别字,这完全是从记忆中获得的!

+0

非常感谢您的回复。这正是我所期待的。 – 2015-02-05 22:21:45