gpt4 book ai didi

c# - 我不能扩展(子类)DataReceivedEventArgs?

转载 作者:太空宇宙 更新时间:2023-11-03 11:31:02 24 4
gpt4 key购买 nike

我正在尝试扩展 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) 更改您正在使用的委托(delegate)的签名,那么您仍然可以使用带有签名的方法进行订阅 void MyEventHandler(object sender, EventArgs e) 感谢委托(delegate)参数的逆变,然后检查 EventArgs 参数的实际类型。

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

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

理想的选择是重新定义委托(delegate)类型以匹配您的包装器,但上述方法可行。

关于c# - 我不能扩展(子类)DataReceivedEventArgs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7770500/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com