SoFunction
Updated on 2025-03-07

How to use lambda to achieve the hooking of delegated events in C#

Delegation definition is as follows:

Copy the codeThe code is as follows:

public class SocketSp
{
 public delegate void ReceiveCompleted(byte[] receiveBuffer, int receiveTotalLen,Exception ex);
 public ReceiveCompleted receiveCompleted;
}

The attachment party is defined as follows
Copy the codeThe code is as follows:

public class LinkOuter
{
 SocketSp linkOuterSocket = new SocketSp();


       private void test(Socket requestHandleSocket)
      {
//The event is to be attached here, and you also want to pass the parameter requestHandleSocket in for subsequent processing.
      }
}


The first idea is to use delegate, but it failed. Because even though the parameters sent by the commission are lost, the subsequent operations cannot be performed.
Copy the codeThe code is as follows:

private void test(Socket requestHandleSocket)
{
+= delegate {
//To do
};
}

The second idea is to use Action, but it also failed. IDEPrompt delegationActionNot adopted3Parameters。
Copy the codeThe code is as follows:

private void test(Socket requestHandleSocket)
{
+= (Action)((outerReceiveBuffer, totalLen, ex) => {
//To do
});
}

The third idea is to use lambda expressions, first attach to the delegate, and at the same time use the call of local variables to implement the parameter passing into the sendResponse function for subsequent operations.
Copy the codeThe code is as follows:

private void test(Socket requestHandleSocket)
{
+= new ((outerReceiveBuffer,totalLen,ex) =>
{
byte[] realOuterReceiveBuffer = new byte[totalLen];
(outerReceiveBuffer, 0, realOuterReceiveBuffer, 0, totalLen);
sendResponse(requestHandleSocket, realOuterReceiveBuffer,"200 OK", "text/html");
});
}

Finally, it was implemented using a lambda expression.