在阅读文章“匿名方法” (作为系列文章“代表和Lambda表达式在C#3.0”的一部分)的一句话:
我变得有点困惑。
IMO通过方法的返回类型,类型由参数表确定,但不(现在还不能,但据我记得找到)。 这是对的吗?
所以,A型参数方法或委托的怎么能有什么不同?
示出对于相同的匿名方法的不同参数的委托类型的任何(最简单的可能)的代码示例,将不胜感激。
参数列表不允许不同。 但与匿名方法,它是合法的,完全省略参数列表。 编译器会知道的参数列表必须是什么样子了,所以没有必要写了。 当然,如果你要使用的参数(你是,通常情况下),那么你必须指定,并将它们命名。
我认为,这说明:
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表达式语法是在这方面有所不同。 她你永远不能忽略的参数。 但是,你可以省略参数类型在许多情况下。 如果恰好有一个参数,而你忽略它的类型,那么你也可以省略括号。