【问题标题】:Assigning methods to events on user controls declared in an interface为接口中声明的用户控件上的事件分配方法
【发布时间】:2011-07-05 20:46:18
【问题描述】:

在 C# 中,我正在构建要在自定义应用程序中使用的自定义控件。我希望每个控件实现一个事件,如果控件内部发生异常或错误(内部检查失败),该事件将触发。我创建了一个声明事件的接口。我创建实现接口的用户控件。这是我的问题。

当我将一个自定义控件添加到表单时,我想遍历表单上的控件,检测属于我的自定义控件的所有控件,然后为我在界面中声明的事件分配一个事件处理程序。我找不到将对象转换为接口类型的方法。

考虑:

interface IMyInterface
{
    event ControlExceptionOccured ControlExceptionOccuredEvent;
...
}

public partial class TextControl : UserControl, IMyInterface {
...
  public event ControlExceptionOccured ControlExceptionOccuredEvent;
...
}

在我的表单上,我使用这些 TextControl 之一。我有这个方法:

private void Form1_Load(object sender, EventArgs e)
{
  foreach (Control Control in Controls)
  {
    if (Control.GetType().GetInterface(typeof(IMyInterface).FullName) != null)
    {
       ((IMyInterface)Control).ControlExceptionOccuredEvent += ControlExceptionHandler;
    }
  }
}

这符合但不会执行。如何将 ControlExceptionHandler 添加到事件链中?

感谢任何试图提供帮助的人。

【问题讨论】:

  • “不会执行”是什么意思?有什么理由不使用if (Control is IMyInterface) 而不是调用GetType 等?

标签: c# events interface


【解决方案1】:

据我了解,如果条件返回 FALSE,您无法订阅该事件。你有没有尝试写这样的东西? :

foreach(Control ctrl in this.Controls){
    if((ctrl as IMyInterface) != null) {
        //do stuff
    }
}

【讨论】:

  • if (ctrl is IMyInterface) {do stuff}一样。
【解决方案2】:

这是一种更简单的方法:

if (control is IMyInterface)
    ((IMyInterface)control).ControlExceptionOccuredEvent += ControlExceptionHandler;

...但是您的操作方式也应该有效,因此您必须提供有关正在发生的事情的更多详细信息。

【讨论】:

    【解决方案3】:

    代码

    ((IMyInterface)Control).ControlExceptionOccuredEvent += ControlExceptionHandler;
    

    生成

    无法将“...Text.TextControl”类型的对象转换为“IMyInterface”类型。

    我不明白为什么不。

    作为旁注,我替换了

    if (Control.GetType().GetInterface(typeof(IMyInterface).FullName) != null)
    

    if (Control is IMyInterface)
    

    它不起作用。第二个示例永远不会返回 true。我也试过了

    if ((Control as IMyInterface) != null)
    

    而且它也永远不会返回 true。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 1970-01-01
      • 2010-12-02
      • 1970-01-01
      • 2010-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多