This article is my newbie's understanding and summary of the commission. Please give me more judgment and advice.
Delegation is a late binding mechanism. To put it bluntly, it is an algorithm that only passes business logic when called.
Delegated creation syntax:
public delegate int Comparison<in T>(T left, T right);//The official definition of generic delegationdemo
The syntax seems to declare a variable or method signature, but implementation is declaring a type. The compiler will generate a derived class (and derived from), the type name is the same as the delegate name, which includes methods such as Invoke, BeginInvoke, and EndInvoke. The compiler also generates add and delete processing services for this new type so that clients of the class can add and delete methods in the call list of instances.
Delegations can be defined inside the class, under the namespace (same level as the class), and under the global namespace (not recommended).
//Define globallypublic delegate int Comparison<in T>(T left, T right); namespace Test { //Define under the specified namespace public delegate int Comparison2<in T>(T left, T right); public class Student { //Define inside the class public delegate int Comparison3<in T>(T left, T right); } }
Definition assignment
Use the delegate as a class (the delegate itself is a class).
//Define the delegationpublic delegate int Comparison<in T>(T left, T right); public class Test { //definition private Comparison<int> comparator; public void Show() { //Assign Please note that the method name is used without brackets, and the method is attached to the delegate as the calling method of the delegate. = Compare; //Call (1, 2); //Call method two (1, 2); } private int Compare(int left, int right) => (right); }
When the target method used as a delegate is a "small method", the lambda expression syntax is usually used to perform the assignment:
Comparison<string> comparer = (left, right) => ();
Multicast delegation
Usually just attaching a single target method to the delegate. However, the delegate object does support attaching multiple target methods to a call list of delegate objects, called multicast delegates. A multicast delegate means that multiple methods can be called when called through a delegate, so multiple methods can be attached to the delegate.
private int Cal(int num) {return num * num;} private void button1_Click(object sender, EventArgs e) { Func<int, int> action = null; //Use += or -= to add or remove delegate instances action += a => { ($"The{1}Time execution" + a); return a + 1; }; action += Cal; action += a => { ($"The{3}Time execution" + a); return a + 3; }; action -= Cal; //If there is a return value, the result of the last execution is returned int a = action(5); (a); }
Commonly used generic delegates
No return value
public delegate void Action(); public delegate void Action<in T>(T arg); public delegate void Action<in T1, in T2>(T1 arg1, T2 arg2); // Other variations removed for brevity.
There is a return value
public delegate TResult Func<out TResult>(); public delegate TResult Func<in T1, out TResult>(T1 arg); public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2); // Other variations removed for brevity
Return to bool type
public delegate bool Predicate<in T>(T obj);
Note:In the .net core platform, asynchronous calls to delegate target methods are not supported.(i.e., the BeginInvoke method is not supported):
Action action = () => ("Terminated execution"); AsyncCallback asyncCallback = a => ("Callback executed" + a); //:“Operation is not supported on this platform.” IAsyncResult result = (asyncCallback, "asdf"); //Delegate to start asynchronous call (result);
Event Event
Events are instances of delegates with event keywords, and event can be restricted from being called externally (invoke) and being assigned directly (=). A delegate is a type, and an event is an instance of a delegate type.
Declaring an event is simple, just add the event keyword when declaring a delegate object.
/// <summary> /// Define a delegate/// </summary> /// <param name="name"></param> public delegate void ShowInfo(string name); public class Study { /// <summary> /// Declare an event /// </summary> public event ShowInfo ShowInfo; public void Show() { ShowInfo += Study_ShowInfo; // Can only be called in the "publisher" class ShowInfo("asdf"); } private void Study_ShowInfo(string name) { throw new NotImplementedException(); } }
Delegation can be used in places where events are used, but events have a series of rules and constraints to ensure the safety and control of the program. Events only have += and -= operations, so that subscribers can only have subscribe or unsubscribe operations and have no permission to perform other operations. If it is a delegate, then the subscriber can use = to reassign the delegate object (all other subscribers are unsubscribed), and even set it to null, and even the subscriber can call the delegate directly. These are very dangerous operations, and the broadcaster loses exclusive control.
Events ensure the security and robustness of the program.
The above is the detailed content of common usage of c# delegation. For more information about c# delegation, please pay attention to my other related articles!