使用事件处理程序传递附加参数或对象
我觉得这确实很基本,但我在这个问题上遇到了麻烦。我正在使用 Process
对象并订阅 DataReceivedEventHandler
。然后,此事件处理程序委托给另一个方法,在本例中为“DoSomething”,参数的签名为 (Object sender, DataReceivedEventArgs args)。我需要做的是扩展一些东西,或者提供一些可以传递附加信息的东西。这是我当前的代码:
// an object of some type
MyCustomObject obj = new MyCustomObject();
// set up obj and Process
process.OutputDataReceived += new DataReceivedEventHandler(DoSomething);
public void DoSomething(Object sender, DataReceivedArgs args)
{
// do some stuff, however, I need the "obj" object passed in for work
}
我觉得这真的很微不足道,但不知道如何继续。我读过有关子类化“EventArgs”的内容,但不确定这将有何帮助,或者甚至不确定如何更改“DoSomething”的签名以接受 DataReceivedArgsExtended
参数,因为 DataReceivedEventHandler 需要一个方法带有 DataReceivedArgs
I feel like this is really basic, but I'm having trouble with this issue. I'm using a Process
object and subscribing to a DataReceivedEventHandler
. This event handler then delegates to another method, in this case "DoSomething", and the signature for the arguments is (Object sender, DataReceivedEventArgs args). What I need to do, is extend something, or provide something that will pass in additional information. Here is my current code:
// an object of some type
MyCustomObject obj = new MyCustomObject();
// set up obj and Process
process.OutputDataReceived += new DataReceivedEventHandler(DoSomething);
public void DoSomething(Object sender, DataReceivedArgs args)
{
// do some stuff, however, I need the "obj" object passed in for work
}
I feel like this is really trivial, but not sure how to proceed. I've read about subclassing the "EventArgs," but not sure how that will help, or how to even change the signature of "DoSomething" to accept a DataReceivedArgsExtended
parameter, since the DataReceivedEventHandler is expecting a method with a DataReceivedArgs
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您可以将 DataReceivedArgs 扩展为 DataReceivedArgsExtended,但请记住将其转换为事件处理程序方法。例如:
Yes you can extend your DataReceivedArgs to DataReceivedArgsExtended, but remeber cast it into event handler method. For example:
您的问题已在以下问题中得到解答:
C# 传递额外参数到事件处理程序?
如何将附加本地对象变量传递给我的事件处理程序? [重复]
在您的情况下,您需要在同一范围内使用
匿名委托函数
或lambda表达式
,并从其中调用您自己的函数,包含事件处理参数和您的附加参数:Your question is already answered in the following questions:
C# passing extra parameters to an event handler?
How can I pass addition local object variable to my event handler? [duplicate]
In your case you need to use an
anonymous delegate function
or alambda expression
in the same scope and from within it call your own function, containing the event handle parameters and your additional ones: