Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/google-chrome/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 关于匿名方法参数的混淆_C#_Anonymous Methods - Fatal编程技术网

C# 关于匿名方法参数的混淆

C# 关于匿名方法参数的混淆,c#,anonymous-methods,C#,Anonymous Methods,在学习匿名方法时,我在互联网上发现了以下示例: namespace AnonymousMethods { public class MyClass { public delegate void MyDelegate(string message); //delegate accepting method with string parameter public event MyDelegate MyEvent; public vo

在学习匿名方法时,我在互联网上发现了以下示例:

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

接受以字符串作为参数的方法。

这两种方法之间有区别

delegate() { ...

第一种方法是不接受参数的匿名方法,而后者完全忽略了参数列表。在本例中,编译器为您推断参数。当您实际上不需要参数值时,可以使用此表单

delegate { ...