关于匿名方法参数的困惑
在学习匿名方法时,我在互联网上找到了以下示例:
namespace AnonymousMethods
{
public class MyClass
{
public delegate void MyDelegate(string message); //delegate accepting method with string parameter
public event MyDelegate MyEvent;
public void RaiseMyEvent(string msg)
{
if (MyEvent != null) MyEvent(msg);
}
}
class Caller
{
static void Main(string[] args)
{
MyClass myClass1 = new MyClass();
// here the confusion
myClass1.MyEvent += delegate
{
Console.WriteLine("we don't make use of your message in the first handler");
};
myClass1.MyEvent += delegate(string message)
{
Console.WriteLine("your message is: {0}", message);
};
Console.WriteLine("Enter Your Message");
string msg = Console.ReadLine();
myClass1.RaiseMyEvent(msg);
Console.ReadLine();
}
}
}
我明白为什么这会起作用:
myClass1.MyEvent += delegate(string message){
Console.WriteLine("your message is: {0}", message); }
但为什么这也起作用:
myClass1.MyEvent += delegate {
Console.WriteLine("we don't make use of your message in the first handler"); }
当我们的委托声明如下:
public delegate void MyDelegate(string message);
接受以字符串作为参数的方法。
While learning on anonymous methods, i've found the following example on the internet:
namespace AnonymousMethods
{
public class MyClass
{
public delegate void MyDelegate(string message); //delegate accepting method with string parameter
public event MyDelegate MyEvent;
public void RaiseMyEvent(string msg)
{
if (MyEvent != null) MyEvent(msg);
}
}
class Caller
{
static void Main(string[] args)
{
MyClass myClass1 = new MyClass();
// here the confusion
myClass1.MyEvent += delegate
{
Console.WriteLine("we don't make use of your message in the first handler");
};
myClass1.MyEvent += delegate(string message)
{
Console.WriteLine("your message is: {0}", message);
};
Console.WriteLine("Enter Your Message");
string msg = Console.ReadLine();
myClass1.RaiseMyEvent(msg);
Console.ReadLine();
}
}
}
I understand why this will work:
myClass1.MyEvent += delegate(string message){
Console.WriteLine("your message is: {0}", message); }
But why this works too:
myClass1.MyEvent += delegate {
Console.WriteLine("we don't make use of your message in the first handler"); }
When our delegate is declared like this:
public delegate void MyDelegate(string message);
Accepting methods with string as parameter.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
之间是有区别的
和
。第一个是不带参数的匿名方法,而后者完全省略了参数列表。在这种情况下,编译器会为您推断参数。当您实际上不需要参数值时,可以使用此形式。
There is a difference between
and
The first is an anonymous method that takes no arguments, while the latter omits the parameter list altogether. In this case, the compiler infers the parameters for you. You can use this form when you don't actually need the values of the parameters.