在 C# 中,如何在接口中声明 EventHandler 的子类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/585837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In C#, how do you declare a subclass of EventHandler in an interface?
提问by Omar Kooheji
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?
我假设有一种简单的方法可以做到这一点。我是否必须在单独的文件中显式声明我的事件处理程序?
采纳答案by Marc Gravell
Well, you need to define the args and possibly delegate somewhere. You don't needa second file, but I'd probably recommend it... but the classes should probably not be nested, if that was the original problem.
好吧,您需要定义 args 并可能在某处进行委托。你不需要第二个文件,但我可能会推荐它......但如果这是原始问题,类可能不应该嵌套。
The recommendation is to use the standard "sender, args" pattern; there are two cmmon approaches:
建议使用标准的“sender, args”模式;有两种常见的方法:
1: declare an event-args class separately, and use EventHandler<T>on the interface:
1:单独声明一个event-args类,EventHandler<T>在接口上使用:
public class MySpecialEventArgs : EventArgs {...}
...
EventHandler<MySpecialEventArgs> MyEvent;
2: declare an event-args class and delegate type separately:
2:分别声明一个event-args类和委托类型:
public class MySpecialEventArgs : EventArgs {...}
public delegate void MySpecialEventHandler(object sender,
MySpecialEventArgs args);
....
event MySpecialEventHandler MyEvent;
回答by Mike Scott
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;
}

