C# 中如何利用lambda实现委托事件的挂接
程序员文章站
2024-02-15 10:01:04
委托定义如下:复制代码 代码如下:public class socketsp{ public delegate void receivecompleted(byt...
委托定义如下:
复制代码 代码如下:
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表达式实现了。