C# 为接口中声明的用户控件上的事件分配方法

C# 为接口中声明的用户控件上的事件分配方法,c#,events,interface,C#,Events,Interface,在C#中,我正在构建自定义控件,以便在自定义应用程序中使用。我希望每个控件实现一个事件,该事件将在控件内部发生异常或错误(内部检查失败)时触发。我创建了一个声明事件的接口。我创建实现界面的用户控件。这是我的问题 当我向表单中添加一个自定义控件时,我希望循环表单上的控件,检测属于我的自定义控件的所有控件,然后将事件处理程序分配给我在接口中声明的事件。我找不到将对象强制转换为接口类型的方法 考虑: interface IMyInterface { event ControlException

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

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

考虑:

interface IMyInterface
{
    event ControlExceptionOccured ControlExceptionOccuredEvent;
...
}

public partial class TextControl : UserControl, IMyInterface {
...
  public event ControlExceptionOccured ControlExceptionOccuredEvent;
...
}
在我的表单上,我使用了其中一个文本控件。我有这个方法:

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添加到事件链


我感谢所有试图帮助我的人。

据我所知,如果条件返回FALSE,您将无法订阅事件原因。你试过写这样的东西吗

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

这是一种更简单的方法:

if (control is IMyInterface)
    ((IMyInterface)control).ControlExceptionOccuredEvent += ControlExceptionHandler;
。。。但是,您这样做的方式也应该起作用,因此您必须提供关于发生了什么的更多细节。

代码

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

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

我不明白为什么不

作为旁注,我替换了

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

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

if ((Control as IMyInterface) != null)
它也永远不会返回真值。

你说的“不会执行”是什么意思?有没有理由不使用
if(控件是IMyInterface)
而不是调用
GetType
等?这与
if(ctrl是IMyInterface){do stuff}
相同。
if ((Control as IMyInterface) != null)