What is the reason why events in C # can only be called internally?
This article mainly explains "why events in C# can only be called internally". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is the reason why events in C# can only be called internally?"
When learning delegates and events in C#, there is a doubt that the events defined in the class can be called directly inside the class, while outside the class, events can only add or remove delegate methods
For example, in the following code, a delegate Order is defined in the class Customer, and Order.Invoke () can be called directly within Customer.
Public class Customer {/ / define event public event OrderEventHandler Order; public string? Name; public float? Price; protected void onOrder (OrderEventArgs orderEventArgs) {if (Order! = null) {Order.Invoke (this, orderEventArgs);}}.
On the outside of the class, only delegate methods can be added or removed, and Order.Invoke () cannot be called. Customer.Order.Invoke () will report an error in the following code.
Public class Program {public static void Main (string [] args) {var customer = new Customer (); customer.name = "1"; Waiter waiter = new Waiter (); customer.Order + = waiter.Serve; / / customer.Order.Invoke () cannot compile customer.Think (); customer.Pay () }}
After taking a closer look at teacher Liu Tiemeng's "introduction to C#", I realized that this was the misunderstanding caused by C# grammatical candy. When defining the event,
The following line of code is a common way of definition, which is a concise method of definition
/ / the concise definition of events public event OrderEventHandler Order; while the complete definition of events in C# is as follows: private OrderEventHandler orderEventHandler;// delegation, using private to modify public event OrderEventHandler Order / / events, adding or subtracting {add {this.orderEventHandler + = value to delegate methods } remove {this.orderEventHandler-= value;}}
After using the full write method to define the event, the internal call cannot be called with the event Order, but with the delegate.
Protected void onOrder (OrderEventArgs orderEventArgs) {if (this.orderEventHandler! = null) {/ / call delegate this.orderEventHandler.Invoke (this, orderEventArgs);}}
As you can see, the delegate that we actually call is decorated with private and is private, so it can only be called internally, while the event wraps the private delegate to add or remove delegate methods.
At this point, I believe you have a deeper understanding of "the reason why events in C# can only be called internally". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!