[英]Assigning methods to events on user controls declared in an interface
In C#, I am building custom controls to be used in a custom application.在 C# 中,我正在构建要在自定义应用程序中使用的自定义控件。 I want each control to implement an event that will fire if an exception or error (an internal check failure) occurs inside the controls.我希望每个控件实现一个事件,如果控件内部发生异常或错误(内部检查失败),该事件将触发。 I created an interface that declares the event.我创建了一个声明事件的接口。 I create user controls that implement the interface.我创建实现接口的用户控件。 Here's my problem.这是我的问题。
When I add one of my custom controls to a form, I want to loop through the controls on the form, detect all controls that are my custom controls and then assign an event handler to the event I declare in the interface.当我将一个自定义控件添加到表单时,我想循环访问表单上的控件,检测所有属于我的自定义控件的控件,然后将事件处理程序分配给我在界面中声明的事件。 I cannot find a way to cast an object to the type of the interface.我找不到将 object 转换为接口类型的方法。
Consider:考虑:
interface IMyInterface
{
event ControlExceptionOccured ControlExceptionOccuredEvent;
...
}
public partial class TextControl : UserControl, IMyInterface {
...
public event ControlExceptionOccured ControlExceptionOccuredEvent;
...
}
and on my form I use one of these TextControls.在我的表单上,我使用这些 TextControl 之一。 I have this method:我有这个方法:
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;
}
}
}
This complies but will not execute.这符合但不会执行。 How can I add ControlExceptionHandler to the event chain?如何将 ControlExceptionHandler 添加到事件链?
My thanks to anyone who tries to help.我感谢任何试图提供帮助的人。
As much as I understand yuo're not able to subscribe to the event cause IF condition returns FALSE.据我了解,如果条件返回 FALSE,您将无法订阅该事件。 Did yuo try to write something like this?你有没有试过写这样的东西? : :
foreach(Control ctrl in this.Controls){
if((ctrl as IMyInterface) != null) {
//do stuff
}
}
This is a simpler way to do it:这是一种更简单的方法:
if (control is IMyInterface)
((IMyInterface)control).ControlExceptionOccuredEvent += ControlExceptionHandler;
... But the way you're doing it should work too, so you'll have to provide more details about what's happening. ...但是您的操作方式也应该有效,因此您必须提供有关正在发生的事情的更多详细信息。
The code编码
((IMyInterface)Control).ControlExceptionOccuredEvent += ControlExceptionHandler;
generates生成
Unable to cast object of type '...Text.TextControl' to type 'IMyInterface'.无法将类型为“...Text.TextControl”的 object 转换为类型“IMyInterface”。
I do not understand why not.我不明白为什么不。
As a side note, I replaced作为旁注,我替换了
if (Control.GetType().GetInterface(typeof(IMyInterface).FullName) != null)
with和
if (Control is IMyInterface)
and it does not work.它不起作用。 The second example never returns true.第二个示例永远不会返回 true。 I also tried我也试过
if ((Control as IMyInterface) != null)
and it also never returns true.它也永远不会返回 true。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.