在“匿名方法”一文 (作为“C# 3.0中的代表和Lambda表达式”系列文章的一部分)中阅读了以下短语:
delegate { return Console.ReadLine() != ""}
)。这是不典型的,但允许在多个场景中出现相同的匿名方法,即使委托类型可能会更改“*”。我有点糊涂了。
IMO (现在找不到,但据我记忆所知),类型是由参数列表决定的,而不是由方法的返回类型决定的。这是正确的吗?
那么,无参数方法或委托的类型如何不同呢?
最好使用任何(最简单的)代码示例来说明同一匿名方法的不同无参数委托类型。
发布于 2013-02-13 01:06:48
参数列表不允许不同。但是使用匿名方法,完全省略参数列表是合法的。编译器将知道参数列表必须是什么样子,所以不需要编写它。当然,如果要使用参数(通常是这样的),则必须指定并命名它们。
我认为这说明:
internal delegate void NoParameters();
internal delegate void SomeParametersThatYouMightNotUse(int i, ref string s, Uri uri);
那么,以下内容是合法的:
NoParameters f = delegate { Console.WriteLine("Hello"); };
SomeParametersThatYouMightNotUse g = delegate { Console.WriteLine("Hello"); };
注意,关键字( ... )
后面没有括号delegate
。
但是,如果您在括号中指定了参数,当然它们必须匹配类型:
NoParameters f = delegate() { Console.WriteLine("Hello"); };
SomeParametersThatYouMightNotUse g = delegate(int i, ref string s, Uri uri) { Console.WriteLine("Hello"); };
在所有情况下,当调用委托时,使用正确的参数:
f();
string myString = "Cool";
g(42, ref myString, new Uri("http://stackoverflow.com/"));
Lambda表达式语法在这方面有点不同。她你永远不能忽略参数。但在许多情况下,您可以省略参数的类型。如果只有一个参数,并且省略了它的类型,那么也可以省略括号。
https://stackoverflow.com/questions/14849195
复制