2

我觉得这真的很基本,但是我在这个问题上遇到了麻烦。我正在使用一个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 的方法

4

2 回答 2

4

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

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 );
 }
于 2011-10-13T16:10:39.320 回答
0

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

C# 将额外参数传递给事件处理程序?

如何将添加的本地对象变量传递给我的事件处理程序?[复制]

在您的情况下,您需要在同一范围内使用 ananonymous delegate function或 a并在其中调用您自己的函数,其中包含事件句柄参数和您的附加参数:lambda 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
}
于 2014-11-16T12:28:28.990 回答