[英]Why can't a sub implement an interface and handle event at the same time?
Why can't a sub implement an interface and handle event at the same time? 为什么sub不能同时实现接口和处理事件?
The following gives my a syntax error: 以下是我的语法错误:
Sub MySub() Handles MyButton.Click Implements MyInterface.MyMethod
End Sub
I know I could handle this kind of logic with another method, but that is not the point. 我知道我可以用另一种方法处理这种逻辑,但这不是重点。 I just want to understand the reasoning behind this. 我只是想了解这背后的原因。
The syntax error is consistent with the language grammar, in §9.2.1 of the VB language specification 1 : 语法错误与语言语法一致,在VB语言规范1的 §9.2.1中:
SubDeclaration ::= SubDeclaration :: =
[ Attributes ] [ ProcedureModifier+ ] SubSignature [ HandlesOrImplements ] LineTerminator [Attributes] [ProcedureModifier +] SubSignature [HandlesOrImplements] LineTerminator
Block 块
End Sub StatementTerminator End Sub StatementTerminator
and 和
HandlesOrImplements ::= HandlesClause | HandlesOrImplements :: = HandlesClause | ImplementsClause ImplementsClause
So only one is supported on any one method. 因此,任何一种方法都只支持一种方法。 The specification doesn't (on a quick view) include a rationale for this limitation. 该规范没有(快速查看)包含此限制的基本原理。 For that you'll need to talk to someone on the VB language design team at Microsoft. 为此,您需要与Microsoft的VB语言设计团队的人员交谈。
1 This is included with an installation of VS under ‹ VSRoot ›\\VB\\Specifications\\1033. 1这包含在< VSRoot > \\ VB \\ Specifications \\ 1033下的VS安装中。
I've never seen any detailed discussion of why this decision was made by the VB.NET team, but to be honest, I struggle to see how this makes any sense from an OOP design perspective. 我从未见过有关为什么这个决定是由VB.NET团队做出的详细讨论,但说实话,我很难从OOP设计的角度看看这有什么意义。 Event handler methods generally shouldn't be doing any work. 事件处理程序方法通常不应该做任何工作。 Rather, they should call out to other methods to do the heavy lifting. 相反,他们应该呼唤其他方法来进行繁重的工作。 The other method that they call out to would be the one that implements your interface. 他们调用的另一种方法是实现接口的方法。
But it's certainly attainable if you do something like this: 但是,如果你做这样的事情,它肯定是可以实现的:
Public MustInherit Class MyParentClass
Protected WithEvents MyButton As Button
Protected MustOverride Sub MySub() Handles MyButton.Click
End Class
Public Class MyDerivedClass : Inherits MyParentClass : Implements IMyInterface
Protected Overrides Sub MySub() Implements IMyInterface.MyMethod
' Do something here...
End Sub
End Class
Also remember that event handler methods generally have a distinctive signature; 还要记住,事件处理程序方法通常具有独特的签名; something like: 就像是:
Public Sub MySub(ByVal sender As System.Object, ByVal e As System.EventArgs)
which is another reason why it would be extremely uncommon for an event handler method to also be able to implement a method defined in an interface. 这也是为什么事件处理程序方法也能够实现接口中定义的方法非常罕见的另一个原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.