What do permit anonymous parameterless delegate ty

2019-05-10 15:27发布

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

  • "Advanced Topic: Parameterless Anonymous Methods

    ... 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"*

I became a little confused.

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.

1条回答
混吃等死
2楼-- · 2019-05-10 16:09

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.

I think this illustrates:

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"); };

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 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.

查看更多
登录 后发表回答