Why can't you implement an interface and handle an event at the same time?

Why can't you implement an interface and handle an event at the same time?

The following is a syntax error:

Sub MySub() Handles MyButton.Click Implements MyInterface.MyMethod End Sub 

I know that I could deal with this logic with another method, but that is not the point. I just want to understand the reasons for this.

+4
source share
2 answers

The syntax error corresponds to the language grammar in section 9.2.1 of the VB 1 language specification:

SubDeclaration :: =
[Attributes] [ProcedureModifier +] SubSignature [HandlesOrImplements] LineTerminator
Block
End Sub StatementTerminator

and

HandlesOrImplements :: = HandlesClause | ImplementsClause

Thus, one method is supported for only one method. The specification does not (at a quick glance) include the rationale for this limitation. To do this, you need to talk to someone on the VB language development team at Microsoft.


1 This is included in the VS installation under \ VB \ Specifications \ 1033.

+4
source

I have never seen a detailed discussion of why this decision was made by the VB.NET team, but to be honest, I am trying my best to understand how this makes sense in terms of OOP design. Event handler methods usually should not do any work. Rather, they should turn to other methods to make a heavy lift. Another method they invoke will be the one that implements your interface.

But this is certainly possible 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 usually have a distinctive signature; sort of:

 Public Sub MySub(ByVal sender As System.Object, ByVal e As System.EventArgs) 

which is another reason why it would be extremely unusual for the event handler method to also implement the method defined in the interface.

+3
source

Source: https://habr.com/ru/post/1347749/


All Articles