When learning delegates and events in C#, a question arises: 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, the following code defines a delegate Order in the Customer class, which can be called directly within the Customer ()
public class Customer { // Define events public event OrderEventHandler Order; public string? name; public float? price; protected void onOrder(OrderEventArgs orderEventArgs) { if(Order != null) { (this, orderEventArgs); } } ......
Outside the class, you can only add or remove the delegate method, and cannot call (). In the following code, an error will be reported.
public class Program{ public static void Main(string[] args) { var customer = new Customer(); = "1"; Waiter waiter = new Waiter(); += ; // () This way, it cannot be compiled (); (); } }
After carefully reading Teacher Liu Tiemeng's "Detailed Explanation of C#" I realized that this is the misunderstanding caused by C# grammatical sugar. When defining events,
The following line of code is a common way of definition, which is a concise way of definition
// Concise way of defining eventspublic event OrderEventHandler Order; andCThe complete definition of events in # is as follows: private OrderEventHandler orderEventHandler;//Trust, use private to modify public event OrderEventHandler Order // Event, increase or decrease the delegate method { add { += value; } remove { -= value; } }
After defining events using the complete writing method, internal calls cannot be called with event Order, but delegate calls should be used to
protected void onOrder(OrderEventArgs orderEventArgs) { if( != null) { // Call delegate (this, orderEventArgs); } }
It can be seen that the delegate we actually call is decorated with private and is private, so it can only be called internally. The event (event) is wrapped to achieve the addition or removal of the delegate method.
I just learned C#, but I don’t know if I have made it clear. . .
This is the article about why events in C# can only be called internally. For more relevant contents of internal calls of C#, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!