【问题标题】:I cannot extend (subclass) DataReceivedEventArgs?我不能扩展(子类)DataReceivedEventArgs?
【发布时间】:2011-10-14 16:15:25
【问题描述】:

我正在尝试扩展 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。

【问题讨论】:

  • 自己制作事件和EventArgs类,不需要派生。
  • 我需要DataReceivedEventArgs中提供的属性:public string Data { get; }
  • 是的,当您提出自己的事件时,这就是您自己的 EventArgs 类所需要的。就像史蒂夫一样。

标签: c# events controls


【解决方案1】:

我怀疑你不能因为构造函数是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;
   }
}

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

【讨论】:

  • 你能用你的最后一句话再解释一下吗?我不确定我是否理解使用这种类型的包装器在哪里会遇到麻烦。
  • 感谢您的更新,我认为这将是一个问题。 process.OutputDataReceived 事件需要一个 DataReceivedEventHandler,它需要一个 DataReceivedEventArgs:public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e)。看来我必须找到另一种方法来获得这种类型的功能
  • 不一定。如果您无法重新定义委托,那么您可以利用委托协方差,这在这种情况下并不理想,但会起作用。我会更新答案。
  • 我已完成以下操作并出现错误:process.OutputDataReceived += new MyEventHandler(TestMethod)。 TestMethod 的签名是:MyEventHandler(object sender, EventArgs e)。错误状态:Cannot convert type project.MyEventHandler to System.Diagnostics.DataReceivedEventHandler。我是不是忘记了什么?
  • 尝试使用process.OutputDataReceived += TestMethod 或 process.OutputDataReceived += new DataReceivedEventHandler(TestMethod)`
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-16
  • 1970-01-01
  • 2015-03-09
  • 2015-11-17
  • 2020-01-26
  • 2020-09-21
相关资源
最近更新 更多