Through the following mind maps, learn the basic concepts of delegation, followed by an emphasis on the use of delegation, hoping to gain more knowledge in the simplest way.
1. Various ways of writing entrusted
1. Delegate delegate name = new delegate (method name that will be invoked); delegate name (parameter);
2. Delegate name = method name that will be invoked; delegate name (parameter);
3. Anonymous methods: delegate name = delegate (parameter) {method body that will be called}; delegate name (parameter);
4. Lamda expression: Delegate delegate name = ((parameter 1,.).Parameter n) =>{method body to be invoked}; delegate name (parameter);
5. Use Action<T>and Func<T>
Action <parameter 1, parameter 2, >delegate name= ((parameter 1, parameter 2) => {method body without return value}); delegate name (parameter 1, parameter 2);
Func<parameter 1, parameter 2, return value>delegate name= ((parameter 1, parameter 2) => {method body with return value}); return value=delegate name (parameter 1, parameter 2);
Example:
public delegate int Call(int num1, int num2); class SimpleMath { // Multiplication Method public static int Multiply(int num1, int num2) { return num1 * num2; } // Division Method public int Divide(int num1, int num2) { return num1 / num2; } } class Test { static void Main(string[] args) { //--------------------First Writing Method------------------------// Call objCall = new Call(SimpleMath.Multiply); Call objCall1 = new Call(new SimpleMath().Divide); //--------------------Second Writing------------------------// Call objCall = SimpleMath.Multiply; Call objCall1 = new SimpleMath().Divide; //--------------------Third Writing Method------------------------// Call objCall = delegate(int a, int b) { return a * b; }; Call objCall1 = delegate(int a, int b) { return a / b; }; //--------------------Fourth Writing Method------------------------// Call objCall =((int a,int b)=> { return a*b;}); Call objCall1 = ((int a, int b) => { return a / b; }); //--------------------Fifth Writing Method------------------------// Func<int, int, int> objCall = ((a, b) => { return a * b; }); Func<int, int, int> objCall1 = ((a, b) => { return a / b; }); Action<int, int> ob = ((a, b) => { Console.WriteLine(a * b); }); ob(5, 3); //----------------------------------------------------// int result = objCall(5, 3); int result1 = objCall1(5, 3); System.Console.WriteLine("Result 1 is {0},Result 2 is{1}", result,result1); Console.ReadKey(); } }
2. Operation of delegation
There are two things to remember about delegated use:
1. Instantiate the delegate object as a parameter;
2. Pass method parameters to the delegate object to implement the actual method call.
Delegate common scenarios:
1. Template method:
The following defines the class CalculateFactory, which defines the various calculation methods, then exposes them for external use through the Calculate method, which calls the Add method by passing in the new Calculate(x1.Add) delegate object.This is a simpler form of the delegate template method and can have many variations.
The program below can fully implement the same logic without delegation. Why bother?Because the example is intended to illustrate the use of delegates as template methods, the simplest type is used, which in practice is usually combined with design patterns to achieve high reuse and low coupling of code.Further extension, delegation is less used in the actual design mode, but interface and abstract class are used to implement the function of "template method". The specific use depends on personal habits and convenience.The most common scenario for delegates is the callback method described below.
class Program { static void Main(string[] args) { CalculateFactory x1 = new CalculateFactory(); CalculateFactory x2 = new CalculateFactory(); x1.Calculate(10, 9, new Calculate(x1.Add)); x2.Calculate(10, 9, new Calculate(x2.Reduce)); Console.ReadKey(); } } public delegate void Calculate(int a, int b); public class CalculateFactory { public void Calculate(int a, int b, Calculate calculateDelegae) { calculateDelegae(a, b); } public void Add(int a, int b) { Console.WriteLine(string.Format("This is a+b={0}", a + b)); } public void Reduce(int a, int b) { Console.WriteLine(string.Format("This is a-b={0}", a - b)); } }
2. Callback method:
The callback method and the template method are not two types side by side, they are the same in nature, that is, the method is passed as a parameter and called, which is classified by the application scenario.A method called a callback method, the body of a method that calls a callback method, is called a callback method when a condition is met or a logic is completed.Turn the above example into a program with callback methods.
Example: Template and callback methods are used here.The sample code comes from Master Liu TieMeng's example, thank you here.
class Program { static void Main(string[] args) { ProductFactory productFactory = new ProductFactory(); WrapFactory wrapFactory = new WrapFactory(); Func<Product> func1 = new Func<Product>(productFactory.MakePizza); Func<Product> func2 = new Func<Product>(productFactory.MakeToyCar); Logger logger = new Logger(); Action<Product> log = new Action<Product>(logger.Log); //Log Delegation of; Box box1 = wrapFactory.WrapProduct(func1, log); Box box2 = wrapFactory.WrapProduct(func2, log); Console.WriteLine(box1.Product.Name); } class Product //Product Class { public string Name { get; set; } public double Price { get; set; } } class Box //Box class { public Product Product { get; set; } } class Logger { public void Log(Product product) { Console.WriteLine(product.Price); } } class WrapFactory //Packaging Factory { public Box WrapProduct(Func<Product> getProduct, Action<Product> logCallback) { Box box = new Box(); Product product = getProduct.Invoke();//Indirect synchronous calls are used here, and BeginInvoke() is used if indirect asynchronous calls are used; if (product.Price > 50) //If the product price is greater than 50, a callback method is implemented; { logCallback(product); } box.Product = product; return box; } } class ProductFactory //Product Factory { public Product MakePizza() { Product product = new Product(); product.Name = "Pizza"; product.Price = 30; return product; } public Product MakeToyCar() { Product product = new Product(); product.Name = "ToyCar"; product.Price = 100; return product; } } }
3. Summary
The basic content of delegation is these, and callback methods are the most used in practice. The above examples of callback methods are useful and need to be well understood.Delegation also has advanced applications such as multicast delegation, which are not described here, but its concepts need to be understood so that when you encounter a scenario, you can flip through the data to find a solution.