Why does a base class event call a private method?

I have a question regarding raising base class events. I am currently reading the C # MSDN Programming Guide, and I cannot understand one thing from the following article:

http://msdn.microsoft.com/en-us/library/vstudio/hy3sefw3.aspx

public void AddShape(Shape s) { _list.Add(s); s.ShapeChanged += HandleShapeChanged; } 

OK, so we register the delegate with the event, and when the event is called, the private HandleShapeChanged method will be called.

 public void Update(double d) { radius = d; area = Math.PI * radius * radius; OnShapeChanged(new ShapeEventArgs(area)); } protected override void OnShapeChanged(ShapeEventArgs e) { base.OnShapeChanged(e); } 

And here we call the OnShapeChanged base class method, which, if successful, will fire the event. But the event is based on the Shape class, so how can it access the HandleShapeChanged method, which is private?

I just started to learn the language, so please carry me. My understanding of this example may not be practical.

+6
source share
2 answers

I see how you think it seems that another class is invoking a private method. But no, the best way to think about access rules is when the delegate is created , not when it is called. And this, of course, is not a problem, the class can access its own private method.

Also checking this when called will be disgusting, which would require the event handler to be publicly available. And event handling is almost always a very private detailing of a class implementation, which should never allow an external code to call directly. Since this would mean that you could not be sure of your event handler that this event actually caused the call. This is bad, very bad.

+10
source

The event invokes the delegate. It doesn't matter what code is in the delegate. Because the method is not explicitly called, access rules are not applied.

We also note that this has nothing to do with the fact that the event is in the base class. The same thing would happen even if the event was in a completely unrelated class.

+9
source

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


All Articles