使用事件处理程序传递其他参数或对象

时间:2011-10-13 15:49:03

标签: c# delegates event-handling eventargs

我觉得这是非常基本的,但我遇到了这个问题。我正在使用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的方法

2 个答案:

答案 0 :(得分:4)

是的,您可以将DataReceived Args扩展到DataReceivedArgs Extended,但请记住将其转换为事件处理程序方法。例如:

public class MyObject
{
    public event EventHandler<MyEventArgs> OnFire;

    public void Fire()
    {
        if( OnFire != null )
        {
            //var e = new MyEventArgs { X=2 };

            var e = new MyEventArgsNew { X = 3, Y = 4 };

            OnFire( this, e );
        }
    }
}

public class MyEventArgs : EventArgs
{
    public int X { get; set; }
}

public class MyEventArgsNew : MyEventArgs
{
    public int Y { get; set; }
}

static void Main( string[] args )
{
        var obj = new MyObject();

        obj.OnFire += new EventHandler<MyEventArgs>( obj_OnFire );

        obj.Fire();

        Console.ReadLine();
 }

 static void obj_OnFire( object sender, MyEventArgs e )
 {
        var e2 = (MyEventArgsNew)e;

        Console.WriteLine( e2.X );
        Console.WriteLine( e2.Y );
 }

答案 1 :(得分:0)

您的问题已在以下问题中得到解答:

C# passing extra parameters to an event handler?

How can I pass addition local object variable to my event handler? [duplicate]

在您的情况下,您需要在同一范围内使用anonymous delegate functionlambda expression,并在其中调用您自己的函数,其中包含事件句柄参数和其他参数:

// an object of some type
MyCustomObject obj = new MyCustomObject();

// set up obj and Process

process.OutputDataReceived +=
    (Object _sender, DataReceivedArgs _args) =>
        DoSomething(obj, _sender, _args);

public void DoSomething(Process process, Object sender, DataReceivedArgs args)
{
    // do some stuff
}