Why can't a sub implement an interface and handle event at the same time?
Why can't a su开发者_如何学Gob implement an interface and handle event at the same time?
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 specification1:
SubDeclaration ::=
[ Attributes ] [ ProcedureModifier+ ] SubSignature [ HandlesOrImplements ] LineTerminator
Block
End Sub StatementTerminator
and
HandlesOrImplements ::= HandlesClause | 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.
1 This is included with an installation of VS under ‹VSRoot›\VB\Specifications\1033.
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. 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.
精彩评论