C#利用lambda实现委托事件的挂接
转自:http://www.cdtarena.com/cpx/201307/9287.html
在写一个小程序的时候,碰到了这样的问题,需要用委托来挂接事件,但是又想在这事件中使用局部的变量,而委托一旦定义好后,挂接方就没有办法再添加额外的形参了。那有没有什么 办法,可以实现呢?
委托定义如下:
- 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 http://www.cdtarena.com/qrs.html
- });
- }
第三个想法是利用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表达式实现了。