简体   繁体   中英

What is wrong in this c# 3.0 code?

I have this code below.

 delegate void TestDel(string str);
        static void Main(string[] args)
        {
            TestDel td = name=> Console.WriteLine(name);
            TestDel td = (string name) { Console.WriteLine(name);}
            td("hello");
            Console.ReadLine();
        }

Here I have a delegate TestDel , which is created first by using a lambda expression which goes fine. But the second method where I am using an anonymous method it doesn't compile but if do like below:

TestDel td = delegate(string name) { Console.WriteLine(name);};

Then everything is fine, my confusion is that why can I use lambda expression and not anonymous method while they are same , why do i need to put delegate with anonymous method but not with lambda expression ?

您的第二个示例应该是:

TestDel td = (string name) => { Console.WriteLine(name); };

由于匿名方法使用delegate关键字创建的: http : //msdn.microsoft.com/zh-cn/library/0yw3tz5k%28v=vs.80%29.aspx这就是该语言的工作方式。

Lambda expressions and anonymous methods are separate language features. A lambda looks like this:

a => Something(a)

And an anonymous method looks like this:

delegate (string a) { Something(a); }

Think of it as the difference between an anonymous type and a class, where the lambda is the anonymous method, and the delegate is the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM