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

5

假设我想迭代一个string[][],使用匿名类型附加值并在结果上执行通用的ForEach-Extensionmethod(很好的例子,我知道,但我想你会明白要点!)。

这是我的代码:

//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);
}
1个回答

8
您不需要明确指定类型,因为它可以从提供的参数中推断出来。
attrs.Select(item => new 
                     { 
                         name = HttpContext.GetGlobalResourceObject("Global", 
                                                      item[0].Remove(0, 7)), 
                         value = item[1] 
                     })
     .ForEach(x => x.name = "something");

请再仔细阅读我的回答,它已经回答了你的问题。关键在于:类型推断。在我的例子中,x 就是那个匿名类型。 - Daniel Hilgarth
1
噢,好的,没错!谢谢你,我会尽快接受的。另外,明确指定类型可能不太可能,对吧? - Dennis Röttger
没错。你无法明确指定它。 - Daniel Hilgarth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接