匿名无参数委托类型有何不同? [英] What do permit anonymous parameterless delegate types to differ?

查看:107
本文介绍了匿名无参数委托类型有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已阅读文章匿名方法 (作为文章系列 C#3.0中的委托和Lambda表达式的一部分),短语:

Having read in article "Anonymous Methods" (as part of the articles series "Delegates and Lambda Expressions in C# 3.0") the phrase:


  • 高级主题:无参数匿名方法

...允许匿名方法省略参数列表( delegate {return Console.ReadLine( )!=} ,例如)。虽然这是非典型的,但即使委托类型,它也会允许相同的匿名方法出现在多种情况下可能会有所不同 *

... anonymous methods are allowed to omit the parameter list (delegate { return Console.ReadLine() != ""}, for example). This is atypical, but it does allow the same anonymous method to appear in multiple scenarios even though the delegate type may vary"*

我变得有些困惑。

IMO(目前无法找到,但据我所知),其类型由参数列表确定,而不由方法的返回类型确定。这是对的吗?

IMO (can't find now but as far as I remember), the type is determined by parameter list but not by return type of a method. Is it correct?

那么,无参数方法或委托的类型如何不同?

So, how can the types of a parameterless method or a delegate differ?

任何(最简单的)代码示例都可以说明同一匿名方法的不同无参数委托类型。

Any (simplest possible) code example illustrating the differing parameterless delegate type for the same anonymous method would be appreciated.

推荐答案

不允许允许参数列表不同。但是使用匿名方法,完全省略参数列表是合法的。编译器将知道参数列表必须看起来像什么,因此无需编写它。当然,如果要使用参数(通常是这样),则必须指定并命名它们。

The parameter lists are not allowed to differ. But with the anonymous method, it is legal to omit the parameter list entirely. The compiler will know what the parameter list must look like already, so no need to write it. Of course, if you are going to use the parameters (which you are, usually), then you have to specify and name them.

我认为这说明了:

internal delegate void NoParameters();

internal delegate void SomeParametersThatYouMightNotUse(int i, ref string s, Uri uri);

那么以下内容是合法的:

Then the following is legal:

NoParameters f = delegate { Console.WriteLine("Hello"); };
SomeParametersThatYouMightNotUse g = delegate { Console.WriteLine("Hello"); };

注意,没有括号(...)在关键字 delegate 之后。

Note, no parenthesis ( ... ) after keyword delegate.

如果,但是,请在括号中指定参数,当然,它们必须与以下类型匹配:

If, however, you specify the parameters in parenthesis, of course they must match the type:

NoParameters f = delegate() { Console.WriteLine("Hello"); };
SomeParametersThatYouMightNotUse g = delegate(int i, ref string s, Uri uri) { Console.WriteLine("Hello"); };

在所有情况下,当您调用委托时,请使用正确的参数:

In all cases, when you invoke the delegate, use the correct parameters:

f();

string myString = "Cool";
g(42, ref myString, new Uri("http://stackoverflow.com/"));

Lambda表达式语法在这方面略有不同。她,您永远无法省略参数。但是在许多情况下,您可以省略参数的类型。而且,如果只有一个参数,而您省略了它的类型,那么您也可以省略括号。

Lambda expression syntax is a little different in this respect. Her you can never omit the parameters. But you can omit the types of the parameters in many cases. And if there is exactly one parameter, and you omit its type, then you can also omit the parenthesis.

这篇关于匿名无参数委托类型有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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