简体   繁体   中英

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. 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.

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. 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?

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. 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'.

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. I also tried

if ((Control as IMyInterface) != null)

and it also never returns true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM