2011-05-30 56 views
4

我们只需说我想遍历string[][],使用匿名类型追加一个值并对结果执行通用的ForEach-扩展方法(辉煌的例子,我知道,但我想你会得到它的精神!)。使用匿名类型调用通用方法(C#)

这里是我的代码:

//attrs = some string[][] 
attrs.Select(item => new { name = HttpContext.GetGlobalResourceObject("Global", item[0].Remove(0, 7)), value = item[1] }) 
      .ForEach</*????*/>(/*do stuff*/); 

正是我会把什么的foreach类型参数?

这里的ForEach样子:

public static void ForEach<T>(this IEnumerable<T> collection, Action<T> act) 
{ 
    IEnumerator<T> enumerator = collection.GetEnumerator(); 
    while (enumerator.MoveNext()) 
     act(enumerator.Current); 
} 

回答

8

你并不需要显式地指定类型,因为它可以从提供的参数来推断:

attrs.Select(item => new 
        { 
         name = HttpContext.GetGlobalResourceObject("Global", 
                 item[0].Remove(0, 7)), 
         value = item[1] 
        }) 
    .ForEach(x => x.name = "something"); 
+0

请再次阅读我的答案。它回答你的问题。重点是:**类型推断**。在我的例子中'x'是那个匿名类型。 – 2011-05-30 11:43:19

+1

哦,真的!谢谢,我会尽快接受。另外,明确指定类型是不可能的,对吗? – 2011-05-30 11:45:36

+0

没问题。你不能明确地指定它。 – 2011-05-30 11:47:13