我无法扩展(子类)DataReceivedEventArgs?

时间:2011-10-14 16:15:25

标签: c# events controls

我正在尝试扩展DataReceivedEventArgs,以便我可以将其他数据传递给正在扩展Process的类。几乎不是在连接到Process.OutputDataReceived时从进程获取数据,我想传入一个控件来写入。

尝试扩展DataReceivedEventArgs时出现错误:

The type 'System.Diagnostics.DataReceivedEventArgs' has no constructors defined

public class DataReceivedArgsWithControl : DataReceivedEventArgs
{
    public Control ControlAdded { get; set; }
}

如何向此Args添加其他属性?我已经扩展了EventArgs本身,因为它有一个构造函数,但不知道如何扩展这个Args。

1 个答案:

答案 0 :(得分:2)

我怀疑你不能因为构造函数是Internal。也许更好的方法是将DataReceivedEventArgs包含在EventArgs派生类中。

class MyDataReceivedEventArgs : EventArgs
{
   DataReceivedEventArgs _inner;

   public MyDataReceivedEventArgs(DataReceivedEventArgs inner, object extraProperty)
   {
      _inner = inner;
      ExtraProperty = extraProperty;
   }

   public object ExtraProperty { get; private set;}
   public DataReceivedEventArgs DataArgs  
   { 
     get
     {
        return _inner;
     }
   }
}

当然,如果您需要DataReceivedEventArgs的多态性,这可能不合适。如果您有一个期望DataReceivedEventArgs的事件处理程序,那么它将无法与包装类一起使用。例如:

public void MyHandler(object sender, DataReceivedEventArgs e) { ... }

这只能接收DataReceivedEventArgs实例或派生类型的实例,而您的包装器不是。所以这取决于你是否需要处理你的自定义EventArgs类,如果它在任何地方都是DataReceivedEventArgs

UPDATE -

如果您无法从public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e)更改您正在使用的委托的签名,那么由于委托参数的逆转,您仍然可以使用签名为void MyEventHandler(object sender, EventArgs e)的方法进行订阅,然后检查EventArgs参数的实际类型。

public void MyEventHandler(object sender, EventArgs e)
{
   var dataEventArgs = e as MyDataReceivedEventArgs;

   if(dataEventArgs != null
   {
      var extendedProperty = dataEventArgs.ExtraProperty;
      var innerArgs = dataEventArgs.DataArgs;
   }
}

理想的选择是重新定义委托类型以匹配您的包装器,但上述方法将起作用。