C# 中如何利用lambda实现委托事件的挂接
public class SocketSp
{
public delegate void ReceiveCompleted(byte[] receiveBuffer, int receiveTotalLen,Exception ex);
public ReceiveCompleted receiveCompleted;
}
public class LinkOuter
{
SocketSp linkOuterSocket = new SocketSp();
private void test(Socket requestHandleSocket)
{
//此处要挂接 linkOuterSocket.receiveCompleted 事件,同时想将参数requestHandleSocket传入,以便后续处理。
}
}
第一个想法是利用delegate,但是失败了。因为虽然挂接上去了,委托传进的参数丢了,无法进行后续操作。
代码如下:
private void test(Socket requestHandleSocket)
{
linkOuterSocket.receiveCompleted += delegate {
//To do
};
}
第二个想法是利用Action,结果也失败了。IDE提示委托Action未采用3个参数。
代码如下:
private void test(Socket requestHandleSocket)
{
linkOuterSocket.receiveCompleted += (Action)((outerReceiveBuffer, totalLen, ex) => {
//To do
});
}
第三个想法是利用lambda表达式,先与委托挂接,同时利用局部变量的调用,来实现参数传递到sendResponse函数中,以便后续操作。
代码如下:
private void test(Socket requestHandleSocket)
{
linkOuterSocket.receiveCompleted += new SocketSp.ReceiveCompleted((outerReceiveBuffer,totalLen,ex) =>
{
byte[] realOuterReceiveBuffer = new byte[totalLen];
Array.Copy(outerReceiveBuffer, 0, realOuterReceiveBuffer, 0, totalLen);
sendResponse(requestHandleSocket, realOuterReceiveBuffer,"200 OK", "text/html");
});
}
最终用lambda表达式实现了。