使用匿名类型调用通用方法(C#)

时间:2011-05-30 11:34:15

标签: c# linq generics extension-methods

我们只想说我想迭代一个string[][],使用匿名类型追加一个值并对结果执行一个通用的ForEach-Extension方法(很好的例子,我知道,但我想你会得到它的主旨!)。

这是我的代码:

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

我究竟会在ForEach的Type-Parameter中添加什么?

以下是ForEach的样子:

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

1 个答案:

答案 0 :(得分:8)

您不需要明确指定类型,因为它可以从提供的参数中推断出来:

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