Shadow events in .NET.

VB.NET has the keyword "shadows." Say I have a base class called "Jedi" and a derived class called "Yoda" that inherits from "Jedi". If I declare a method in "Jedi" called "ForcePush" and the shadow that appears in "Yoda", then when I call the method in an instance of the "Yoda" class, it ignores the implementation of the base class and uses the implementation of the derived class, However, if I have an instance of "Yoda" that was originally declared as a type of "Jedi", i.e. Dim j as Jedi = new Yoda() , and called the "ForcePush" method on the instance, it will use the Jedi implementation.

Now let me say that I have an event called “UseForce” that occurs when the “ForcePush” method is called, and I am a shadow event in a derived class (this is because “Yoda” has an “IForcePowers” ​​interface that declares this event), and each class raises the corresponding event.

If I have an instance of "Yoda" that is declared as a type of "Jedi" (as above), and I put the event handler in the "UseForce" event of "Jedi", and then the "ForcePush" method is called in the "Yoda" class, it will Is this an event handler reached?

+6
event-handling shadows
source share
1 answer

Using the shadows keyword in VB.NET means that you are declaring a completely new member that exists outside of any hereditary hierarchy that exists. This is why this keyword (and its associated practice) is usually regarded as “smelly” (although some people object to this particular term, I find it quite appropriate). What is the rationale for this model of "shading things"? This approach is usually reserved for cases where there is no other way to do what you need. Is inheriting and redefining methods not an option?

In any case, if you “obscure” an event in a lower class, then no, there is no way for a class closer to the inheritance chain to trigger the event directly, since they do not suspect that it even exists.

+2
source share

All Articles