如何将 C# lambda 表达式转换为委托?
How do I convert a C# lambda expression into a delegate?
我不是很熟悉 lambda 和委托表达式,但我需要使用 .NET 2 框架,所以我将不得不使用委托。
假设我有一个
的例子
process = new Process();
并且我想通过自定义将附加参数传递给事件:
public void TestHandler(object s, DataReceivedEventArgs e, string mystring)
{
Console.writeLine(e.Data + "," + mystring);
}
...
process.OutputDataReceived += new DataReceivedEventHandler((sender, e) => TestHandler(sender, e, "hello"));
我应该如何使用委托来做到这一点?
我试过这样做:
public delegate void TestDelegate(object s, DataReceivedEventArgs e, string mystring);
..eg inside main
TestDelegate testDel = delegate(object s,DataReceivedEventArgs e, string mystring) { TestHandler (s, e, mystring); };
process.OutputDataReceived += new DataReceivedEventHandler(testDel);
但我想我错了。
我没有太多的上下文,但是 DataReceivedEventHandler 的签名是 public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e);
。它有两个参数,而您正试图传递一个包含三个参数的委托:(object s,DataReceivedEventArgs e, string mystring)
.
我猜你必须删除第三个参数,string mystring
。
如果我没理解错的话,您可以简单地将 lambda 表达式转换为委托(匿名方法表达式),而无需创建新的委托类型。
改变这个:
(sender, e) => TestHandler(sender, e, "hello")
进入
delegate (object sender, DataReceivedEventArgs e) {
TestHandler(sender, e, "hello");
}
我不是很熟悉 lambda 和委托表达式,但我需要使用 .NET 2 框架,所以我将不得不使用委托。
假设我有一个
的例子process = new Process();
并且我想通过自定义将附加参数传递给事件:
public void TestHandler(object s, DataReceivedEventArgs e, string mystring)
{
Console.writeLine(e.Data + "," + mystring);
}
...
process.OutputDataReceived += new DataReceivedEventHandler((sender, e) => TestHandler(sender, e, "hello"));
我应该如何使用委托来做到这一点?
我试过这样做:
public delegate void TestDelegate(object s, DataReceivedEventArgs e, string mystring);
..eg inside main
TestDelegate testDel = delegate(object s,DataReceivedEventArgs e, string mystring) { TestHandler (s, e, mystring); };
process.OutputDataReceived += new DataReceivedEventHandler(testDel);
但我想我错了。
我没有太多的上下文,但是 DataReceivedEventHandler 的签名是 public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e);
。它有两个参数,而您正试图传递一个包含三个参数的委托:(object s,DataReceivedEventArgs e, string mystring)
.
我猜你必须删除第三个参数,string mystring
。
如果我没理解错的话,您可以简单地将 lambda 表达式转换为委托(匿名方法表达式),而无需创建新的委托类型。
改变这个:
(sender, e) => TestHandler(sender, e, "hello")
进入
delegate (object sender, DataReceivedEventArgs e) {
TestHandler(sender, e, "hello");
}