What is delegation
A typical example is when the whole of a method is relatively fixed and a small part of it changes. Sometimes, without delegation, we usually pass a variable to the method. The method judges the specific execution of the changed parts according to the value of this parameter. It is very abstract. The whole chestnut:
using System; namespace DemoDelegate { class Program { static void Main(string[] args) { string input = Console.ReadLine(); string result = HandleString(input, "trim"); Console.WriteLine("I can achieve my goal without commission. result=" + result); } /// <summary> /// Add time before input, and then process accordingly. /// </summary> /// <param name="ActoinType"></param> /// <returns></returns> private static string HandleString(string input, string ActoinType) { switch (ActoinType) { case "trim": input = input.Trim(); break; case "toLowerCase": input = input.ToLower(); break; case "toUpperCase": input = input.ToUpper(); break; default: break; } input = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffffff") + input;//This is what is called fixed operation. return input; } } }
ps: There are some shortcomings in the above code. After reading it, you may think: why not first deal with the part of the change that will be processed in main, and then call it. The answer is: When the method HandleString is sufficiently complex and context-sensitive, the idea is over.
According to the idea of object-oriented encapsulation, this obviously does not meet the requirements of extended open. At this point, naturally, I wonder if we can pass in the changed part in the form of a method. Lamp lamp lamp! Delegation appears
Idea: What type of method does HandleString use to receive this change? It's certainly not about writing a method call in a parameter, because that's equivalent to giving the result to HandleString. It should be a new data type: a type defined by itself. So, let's start with a silly question: How do we define a class?
class CatInfo { public int ID { get; set; } public string Name { get; set; } }
Class itself is a keyword, so we use delegate to define the type of a method class.
public delegate string WhatToDo(string input);
At this point, delete would like to be the class keyword, and this class, not the usual definition of the class, has attributes, fields, methods. It just defines a class of methods, such as an example, which must return a string and input a string in the method signature. This method of defining a class of methods is called delegation.
Let's look at the silly x problem again. How do we instantiate a class?
CatInfo info = new CatInfo();
Similarly, we instantiate a delegate
public static string Method1(string input) { string result = "I'm just a normal way to go back. string. The input parameter is also a string,My input value is:" + input; Console.WriteLine(result); return result; } WhatToDo instrnceOfWhatToDo = Method1;
Yes, without the new keyword, an instance of type type = concrete value (i.e. int a=1). Understanding it carefully, it is nothing more than a method type (delegation), and assigning value to it points to a method. At this time, it is not difficult to understand a complete chestnut:
using System; namespace DemoDelegate { class Program { public delegate string WhatToDo(string input); static void Main(string[] args) { WhatToDo instrnceOfWhatToDo = DoTrim; string input = Console.ReadLine(); string result = HandleString(input,instrnceOfWhatToDo); Console.WriteLine("I will have the same output. result=" + result); } public static string DoTrim(string input) { string result = input.Trim();//Brain tonic here is a very complicated logic to deal with. return result; } private static string HandleString(string input, WhatToDo TheInstanceOfWhatToDo) { input = TheInstanceOfWhatToDo(input); return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffffff") + input; } } }
Summary: Delegation is a method type definition with the same signature information (number and type of input parameters, type of return parameters) except method name.
What's the usage?
In the chestnuts above, it is not easy to reflect the purpose of the commission, but it is also not difficult to realize a little eyebrow: it has the function of disassembling the number of particles in the method. At least as in the example above, there is no need to make a bunch of judgments based on ActoinType parameters, and when there are more variations, the open-close principle will not be violated. According to the defined WhatToDo, it's easy to write an instance of the method assigned to the delegate to debug. (Of course, it's cumbersome to define a method for each extension, and there's not much possibility of reuse. Don't worry. There's a simple way to write it. First dig a hole.
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
What is an event? I'll explain later, dig another hole and fill it later.
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Delegation becomes anonymous
Understanding the basic skills, then to the Commission of the specific play. Fill in the first pit in front.
To do a delegation, get a reputation for one delegation type, another instance, and the method that this instance points to. To quote papi sauce, "Do you mean maltreatment? Abuse not abuse? Abuse! "
At least, the. net framework does a little bit of work for us. Because the input parameters of the method are limited, the. net framework can help us define the delegation type. Make good use of generics.
It's Func and Action. Func has a return value, Action has no return value. Look at the definition:
Func<TResult>
Func<T, TResult>
Func<T1,T2, TResult>
Func<T1,T2,T3 TResult>
.....
Func is a delegation definition that defines N multiple overloads (N is too big to use a method with so many input parameters anyway). From no input parameters, return TResult, to N input parameters, return TResult, are well defined.
See chestnuts
static void Main(string[] args) { Func<string, DateTime, decimal, string> Method1 = MyMethod; Method1("Zhang San", DateTime.Now, (decimal)18.00); } public static string MyMethod(string parms1, DateTime parms2, decimal parms3) { return "I am a by string datetim decimal As an input parameter, return string Method"; }
It's not much different from the most traditional way of writing a delegate, but it's just a lack of defining a delegate type. Use the Func defined by. net framework directly.
Similarly, an Action is a defined delegate, but it does not return a type.
Action
Action<T1>
Action<T1,T2>
Action<T1,T2,T3>
Chestnuts are still needed, even if they are too understandable:
static void Main(string[] args) { Action<string, DateTime, decimal> Method1 = MyMethod; Method1("Zhang San", DateTime.Now, (decimal)18.00); } public static void MyMethod(string parms1, DateTime parms2, decimal parms3) { Console.WriteLine("I am a by string datetim decimal string As an input parameter, there is no method to return a value"); }
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
The change in delegation is certainly more than just. net framework defining several delegation types for us. At this time, the anonymous method appears.
I don't define the type of delegation. Use the Func above, that is, learn to use it.
using System; namespace Demo Anonymous Methods { class Program { static void Main(string[] args) { Func<int, int, int> myMethodPlus = delegate (int a, int b) { return a + b; }; Func<int, int, int> myMethodDivision = delegate (int a, int b) { if (b==0) { return 0; } return a / b; }; } } }
This way of writing is very beautiful. Instead of defining each method individually, you can directly write the method after the delegate instance equals sign. Because the reuse opportunity of this method is close to zero. This is called anonymous method, because it has no method name, but input parameters, return values, then this name.
PS. It's really hard for me to remember its grammar because it's seldom used in my work. What is the most commonly used? Look at the following:
Anonymous methods become lambda expressions
Don't think anonymity is beautiful, C # grammatical sugar so sweet.
We have a lambda expression, this lambda, the Greek symbol lambda that high school math came into contact with. Make entrusted writing more pleasant.
using System; namespace DemoLambda { class Program { static void Main(string[] args) { Func<int, int, int> myMethodPlus = (int a, int b) => { return a + b; }; Func<int, int, int> myMethodDivision = (int a, int b) => { if (b == 0) { return 0; } return a / b; }; int result1 = myMethodPlus(1, 1); int result2 = myMethodDivision(4, 2); } } }
You're right. Even the delegate keyword that Baidu had to translate at the beginning disappeared, replaced by =>. The grammar is (parameter 1, parameter 2, you can write parentheses without one parameter)=> {method body};
Here, you can see the principles of Where (Func < T, bool >), OrderBy (Func (T, TKey) that implement the GetEnumlator method.
Postscript:
Having been a programmer ape for so many years, I've been learning from it, but I haven't shared it. Finally, I have time to write blog for the first time. Thank you for correcting the mistakes.