简体   繁体   中英

In C#, how do you declare a subclass of EventHandler in an interface?

What's the code syntax for declaring a subclass of EventHandler (that you've defined) in an interface?

I create the EventHandler subclass MyEventHandler for example in the delegate declaration, but you can't declare a delegate in an interface...

When I ask Visual Studio to extract an interface it refers to the EventHandler in IMyClassName as MyClassName.MyEventHandler which obviously plays havoc with type coupling.

I'm assuming there is a simple way to do this. Do I have to explicitly declare my event handler in a separate file?

Well, you need to define the args and possibly delegate somewhere. You don't need a second file, but I'd probably recommend it... but the classes should probably not be nested , if that was the original problem.

The recommendation is to use the standard "sender, args" pattern; there are two cmmon approaches:

1: declare an event-args class separately, and use EventHandler<T> on the interface:

public class MySpecialEventArgs : EventArgs {...}
...
EventHandler<MySpecialEventArgs> MyEvent;

2: declare an event-args class and delegate type separately:

public class MySpecialEventArgs : EventArgs {...}
public delegate void MySpecialEventHandler(object sender,
    MySpecialEventArgs args);
....
event MySpecialEventHandler MyEvent;

Assuming C# 2.0 or later...

public class MyEventArgs: EventArgs
{
    // ... your event args properties and methods here...
}

public interface IMyInterface
{
    event EventHandler<MyEventArgs> MyEvent;
}

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