1

我已经离开 C# 一段时间了,现在我正在尝试阅读一些代码,我很难找到它的含义:

var server = new WebSocketServer("ws://localhost:8181");
server.Start(socket =>
{
    socket.OnOpen = () =>
    {
        Console.WriteLine("Open!");
        allSockets.Add(socket);
    };
    socket.OnClose = () =>
    {
        Console.WriteLine("Close!");
        allSockets.Remove(socket);
    };
    socket.OnMessage = message =>
    {
        Console.WriteLine(message);
        allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
    };
});

语法的名称是什么socket => { .. },我在哪里可以找到一些文字?它是在哪个版本的 C# 中引入的?是= () => { .. }一样的吗?

4

2 回答 2

4

It is a lambda expression, basically it is a shortcut for defining delegates, which are anonimous methods. It was introduced in C# 3 along with LINQ to make its use much simpler. Syntax is as follow:

parameters => body

Usually the compiler can infer in some way the type of the parameter, that's why you see only the names of the parameters.

于 2013-02-09T12:39:56.173 回答
1

in c# this syntax is called Lambda Expressions. They are available since C# 3.0

more about:

Microsoft's Programming Guide explaining lambda expression

C# Lambda expressions: Why should I use them?

and an example of programmersheaven.com

于 2013-02-09T12:39:14.410 回答