【发布时间】: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等?