当我运行这两行代码时,我得到了我所期望的结果:
Func<int, int> sqr = x => x * x;
Console.WriteLine(sqr(3));
但我不明白为什么将返回值指定为第二个参数?这一切是如何运作的?定义委托时,它必须是:
return-type delegate delName (parameters);
但是,对于 Func 委托,返回类型也被指定为输入参数。有人可以向我解释一下这一切是如何运作的吗?如果可能的话,使用指定返回类型作为输入参数的相同概念编写一个小示例。我发现很难理解幕后发生的事情。
提前致谢 :)
When I run these 2 lines of code I get what I expect:
Func<int, int> sqr = x => x * x;
Console.WriteLine(sqr(3));
But I don't understand why the return is specified as the 2nd argument? How does it all work? When you define a delegate it has to be:
return-type delegate delName (parameters);
However, with Func delegate, the return type is also specified as the input argument. Can anybody explain me how it all works? And if possible, write a small example using the same concept of specifying the return type as the input parameter. I find it very difficult to understand what is happening under the hood.
Thanks in advance :)
发布评论
评论(3)
您正在谈论的 System.Func 的完整声明是
因此,当您这样做时,
您正在使用 lambda 表达式声明一个方法,该表达式接受 int x 并返回 x * x。所以现在
sqr
持有对您的方法的引用。在下面的行中,您实际执行该方法并显示输出。
The full declaration for
System.Func
you're talking about isSo when you do
You're declaring a method using a lambda expression which takes an int x and returns x * x. So right now
sqr
is holding a reference to your method. And in the following lineYou actually execute the method and show the output.
Eric Lippert 对此发表了一篇很好的文章
我鼓励您阅读这篇文章,但文章的主旨是返回值出现在右侧的原因是它是最自然的位置。它是英语、数学和高阶函数的自然选择。由于历史原因,C# 将返回类型放在首位。
Eric Lippert did a nice article on this
I encourage you to read the article but the gist of the article is that the reason the return value appears on the right is that it's the most natural position for it. It is the natural choice for both the English language, mathematics and higher order functions. C# has the return type first for historical reasons.
它不是“输入参数”,而是 泛型
It is not "input parameter", it is Generics