简体   繁体   English

在C#中,如何在接口中声明EventHandler的子类?

[英]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?在接口中声明 EventHandler 的子类(您已定义)的代码语法是什么?

I create the EventHandler subclass MyEventHandler for example in the delegate declaration, but you can't declare a delegate in an interface...例如,我在委托声明中创建了 EventHandler 子类 MyEventHandler,但您不能在接口中声明委托...

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.当我要求 Visual Studio 提取一个接口时,它会将 IMyClassName 中的 EventHandler 称为 MyClassName.MyEventHandler,这显然会对类型耦合造成严重破坏。

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;建议使用标准的“sender, args”模式; there are two cmmon approaches:有两种常见的方法:

1: declare an event-args class separately, and use EventHandler<T> on the interface: 1:单独声明一个event-args class,在接口上使用EventHandler<T>

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

2: declare an event-args class and delegate type separately: 2:分别声明一个事件参数 class 和委托类型:

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

Assuming C# 2.0 or later...假设 C# 2.0 或更高版本...

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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