In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >
Share
Shulou(Shulou.com)06/01 Report--
Preface
In C # we can customize delegates, but why does C # have built-in generic delegates? Because we often use delegates, if the system has built-in delegates that you might use, you don't have to define delegates and then instantiate them, which makes the code look simple and clean and improves the programmer's development speed. Through this article, you can review the extension method and gradually understand the implementation of the built-in generic delegate and the gradual evolution of the delegate.
Action
Concept: encapsulates a method that has five parameters and returns no value. And the type parameter is inverter.
Next I will customize the implementation of a delegate with no return value for Action. We also define a Person class, it seems that I can never leave the topic of Person in my essays, ! Please look at the following code
Public class Person {public string Name {get; set;} public int Age {get; set;} public bool Gender {get; set;}}
Then simulate the Action delegate through the ForEach method in the console, first define a list GetList () that gets the Person.
Static List GetList () {List list = new List () {new Person () {Name = "Hua Qiangu (descendants of Nuwa and demon gods)", Age = 12, Gender = false}, new Person () {Name = "Baizi painting", Age = 13, Gender = true} New Person () {Name = "Oriental Xianqing (Immortal Cabinet Master and University Bachelor of Shu)", Age = 14, Gender = true}, new Person () {Name = "Qingshui (long staying disciple)", Age = 15, Gender = false}, new Person () {Name = "Meng Xuanlang (Emperor of Shu and long remaining disciple)", Age = 16, Gender = true}} Return list;}
Because we know that when using a delegate, there are several steps:
(1) define delegation
(2) instantiating entrustment
(3) add the method pointer to the instantiated delegate object
But now we do not need to define a delegate, we already have a built-in delegate, we just need to instantiate it, and there is generally a clear method for adding a method pointer. If we only use the method temporarily, we can send anonymous methods to play, so the above three steps can be simplified to two steps. The code is as follows:
Var list = GetList (); list.ForEach (new Action (delegate (Person p) {Console.WriteLine (p.Name);}))
The above code is a bit like the traversal method of Each in jQuery. The result is printed out:
We know that the parameter in the ForEach method is Action action, so we can simply abbreviate it as follows
List.ForEach (delegate (Person p) {Console.WriteLine (p.Name);})
The print result is the same as above. Its code can continue to be more streamlined, not in a hurry, we come step by step.
Predicate
Concept: a method of defining a set of conditions and determining whether a specified object meets those conditions. The return value is of type bool, and the type parameter is inverted.
There is no better way to use this generic delegate than the FindAll () method in List, which filters out a new collection based on criteria from a collection. We just learned about the extension method in the last section, and we can customize the implementation of this method by adding the extension method to the generic collection List to filter according to the parameter conditions of the Predicate delegate.
Static List SelfDefineFindAll (this List list, Predicate pre) / * Note: since the extension method is added, the Program of the console in this example should also be declared as a static class * / {List preList = new List / * data filtered by criteria is added to the collection * / foreach (T t in list) {if (pre (t)) / * filter based on criteria * / {preList.Add (t);}} return preList;}
We query the data that are older than 13 years old and traverse the filtered data according to ForEach. The code is as follows:
Var list = GetList (); var preList = list.SelfDefineFindAll (delegate (Person p) {return p.Age > 13;}); preList.ForEach (delegate (Person p) {Console.WriteLine (p.Name);})
The results print out the correct results, as follows:
Through FindAll in C#, you can achieve the same effect by simply doing the following, but it is not an extension method:
List.FindAll (delegate (Person p) {return p.Name})
In fact, the above code can be more concise, do not worry, we will do it step by step.
Comparison
Concept: represents a method of comparing two objects of the same type. The parameter type is inverter and the return value is int.
List.Sort (new Comparison (delegate (Person p, Person p1) {return p.Age-p1.Age;})); / * Age in order from small to big * /
It can also be abbreviated as:
List.Sort ((delegate (Person p, Person p1) {return p.Age-p1.Age;}); Func
It seems that Func is the most frequently used in actual project development among the system built-in generic delegates.
Concept: encapsulates a method that has one parameter and returns the type value specified by the TResult parameter. The parameter type is inverter, and the return value parameter type is covariant.
The most frequently used delegate is the Select method in the List generic collection, to see how the built-in Select method uses Func to return a new collection.
(1) implement with anonymous method.
Let's next define an Animal class based on the above. Property is the same as the Person class, and the code is as follows:
Public class Animal {public string Name {get; set;} public int Age {get; set;} public bool Gender {get; set;}}
Next we return a new collection, the Animal collection, through the Person collection through the Select method. The code is as follows:
Var list = GetList (); List animalList = list.Select (new Func (delegate (Person p) {return new Animal = p.Name, Age = p.Age, Gender = p.Gender};}). ToList (); animalList.ForEach (delegate (Animal animal) {Console.WriteLine (animal.Name);})
It also prints out the same result when traversing the Person collection, which seems tedious, so let's simplify the code as follows:
Var list = GetList (); List animalList = list.Select ((delegate (Person p) {return new Animal () {Name = p.Name, Age = p.Age, Gender = p.Gender};}) .ToList (); animalList.ForEach (delegate (Animal animal) {Console.WriteLine (animal.Name);})
Let's customize the implementation of the Select () method through the extension method, with the following code:
Public static List SelfDefineSelect (this List list, Func fun) / * T is the incoming generic collection type, and TR is the returned generic collection type * / {List selList = new List (); / * instantiated returned generic collection * / foreach (T t in list) {TR tr = fun (t) / * get the incoming collection data * / selList.Add (tr);} return selList; / * return a new generic collection * /}
This call is still made, and the print result is correct:
List animalList = list.SelfDefineSelect ((delegate (Person p) {return new Animal () {Name = p.Name, Age = p.Age, Gender = p.Gender};}). ToList (); (2) combined with anonymous classes
When we use Func to convert to a new collection based on conditions, we may only need a few instance members. At this time, it would be a bit of a mountain out of a molehill to create a new class for acquisition. In this case, you only need to pass the required or members to an anonymous class. This is the scenario where Func needs to use anonymous classes. So in view of this, we will return the new collection as an anonymous collection instead of an Animal collection, the code modification is as follows:
Var anyousList = list.Select ((delegate (Person p) {return new {Name = p.Name}; / * use * /} with anonymous classes))
Through the implementation of the built-in generic delegate in the system mentioned above, it seems a bit unsatisfactory. The code about the delegate is too tedious. Yes, Microsoft knows this greatly and clearly. So, step by step to the advanced, then the following lambda expression, this structure is simply simple. It makes you feel good.
Lambda expression
The above code said that it can be streamlined. How can it be streamlined? That's the lambda expression. Anonymous methods are concise enough, but lambda expressions are a more concise syntax than anonymous methods! We use lambda expressions to implement the Action, Predicate, and Func delegates in the above, respectively.
Action var list = GetList (); list.ForEach (d = > Console.WriteLine (d.Name);) Predicate var list = GetList (); list.FindAll (d = > d.Age > 13); Func list.Select (d = > Person () {Name = d.Name, Age = d.Age, Gender = > {Name = d.Name})
Well, everything has become so clear. Since the introduction of lambda expressions, the speed of typing the code has accelerated, and my mother no longer has to worry about me staying up late.
Well, the question is, we know that lambda expressions are divided into statement lambda and expression lambda, so what's the difference between the two? Literally, is the statement lambda enclosed in curly braces? Ok, give me the code to understand.
(string str) = > {return str.length;} / * statement lambda (with curly braces and return) * / (string str) = > str.length / * expression lambda (no curly braces and return, only one formula) * /
So the question comes again, what exactly is a lambda expression? We still use decompilation to view list.ForEach (d = > Console.WriteLine (d.Age)); the corresponding C # code is as follows:
Look at the parameter in the ForEach () method, which probably means anonymous method delegate. Then we click in to have a look. The code is as follows:
Let's click Action to have a look, as follows:
It suddenly became clear, which means that the essence of lambda expressions is anonymous methods. So now think about it, the essence of lambda expressions is anonymous methods, and the essence of anonymous methods is through delegation. This should be it.
Evolution process of lambda expression
Let's give an example of an extension method to demonstrate how vividly the evolution of lambda expressions is.
Suppose the following scene: in the flower thousand bones TV to find out the white painting, find the right you win! We get to give a list of the characters of the flower, and then choose the white painting.
/ * find out what you need according to the conditions, return true and you win, otherwise lose * / static bool SelDefine_Extension_IEnumerable (this IEnumerable source, Func func) {foreach (var item in source) {if (func (item)) {return true }} return false;}
The following is a list of collections:
Var list = new List () {"Flower Thousand bones", "Baizi painting", "Oriental Qing Dynasty", "Neon all over the Sky", "Sugar Treasure", "falling National Day", "Light Water", "Meng Xuanlang"}
Then execute the extension method in the console to query, and list the six parts of the lambda expression here:
List.SelDefine_Extension_IEnumerable (
From the beginning of the tedious, complex to the final simplicity, every process Microsoft is to make a certain effort, first point to praise first! Looking at the above with a picture, it is estimated that it will be more clear.
The Evolution of lambda expression in six parts
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.