我正在尝试扩展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。
最佳答案
我怀疑您不能,因为构造函数是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
。更新-
如果您不能从
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;
}
}
理想的选择是重新定义委托类型以匹配您的包装器,但是上述方法将起作用。