C#方法组陌生感 [英] C# method group strangeness

查看:146
本文介绍了C#方法组陌生感的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一些很奇怪的是,我希望能更好地理解

I discovered something very strange that I'm hoping to better understand.

var all = new List<int[]>{
                new int[]{1,2,3},
                new int[]{4,5,6},
                new int[]{7,8,9}
              };

all.ForEach(n => n.ForEach(i => Console.WriteLine(i)));



,可重写为:

which can be rewritten as:

...
all.ForEach(n => n.ForEach(Console.WriteLine));



这怎么还是有可能离开了lambda表达式参数(I =>),并有当前项目传递给console.WriteLine?

How is it possible to leave out the lambda expression parameter (i=>) and still have the current item passed to console.WriteLine?

感谢您的任何见解。
-Keith

Thanks for any insight. -Keith

推荐答案

列表< T> .ForEach 正在寻找一个动作< T> 。当你写

List<T>.ForEach is looking for an Action<T>. When you write

n.ForEach(Console.WriteLine);

在这里有什么方法组控制台的成员之一。的WriteLine 扮演的角色的动作< T> 。编译器会寻找那些吃 INT 的实例 Console.WriteLine 的最佳超载。事实上,它会使用过载 Console.WriteLine(INT) 。然后它会用这个重载发挥动作<的作用; INT>

what you have here is one of the members of the method group Console.WriteLine playing the role of an Action<T>. The compiler will look for the best overload of Console.WriteLine that eats instances of int. In fact, it will use the overload Console.WriteLine(int). It will then use this overload to play the role of an Action<int>.

有关如何的详细信息。完成后,请参阅该规范(方法组转换)的6.6节。

For details on how this is done, see §6.6 of the specification (Method group conversions).

不过,当你写

n.ForEach(i => Console.WriteLine(i));

我们实际上有一个非常不同的动作< INT> 在第一种情况下,动作< INT> Console.WriteLine(INT)。在这里,动作< INT> 相当于写过你

we actually have a very different Action<int> In the first case, the Action<int> was Console.WriteLine(int). Here, the Action<int> is equivalent to you having written

public static void DoSomething(int i) {
    Console.WriteLine(i);
}



然后

and then

n.ForEach(DoSomething);



(当然,编译器必须通过相同的方法组如上所述的方法找出什么是的DoSomething )的意思。

的一点是,在第一种情况下的动作< INT> Console.WriteLine(INT)。然而,在第二种情况下,动作< INT> 是一个中间人(lambda表达式)本身将调用 Console.WriteLine(INT)

The point is that in the first case the Action<int> is Console.WriteLine(int). However, in the second case the Action<int> is a middle man (the lambda expression) that itself will call Console.WriteLine(int).

这篇关于C#方法组陌生感的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆