. NET of those so-called new syntax Two: Anonymous class, anonymous method and extension method

Source: Internet
Author: User
Tags reflector

Opening: In the previous article, we learned about the so-called new syntax for automatic attributes, implicit types, automatic initializers, and so on, which we continue our journey to look at anonymous classes, anonymous methods, and common extension methods. Although, are very common things, but not necessarily we all understand the mystery. So, follow the pace of this article, continue to onlookers.

 /* new Syntax index */ 1. Automatic Properties auto-implemented Properties2. Implicit type Var3. parameter defaults and named Parameters 4. Object initializer and collection initializer {}5. Anonymous classes & anonymous methods 6. Extensions Method 7: The system built-in delegate FUNC/ACTION8.LAMBDA expression 9. Standard query operator, operator10.linq query expression, anonymous class  1.1 I'm sorry, I've been hiding in the development, We sometimes declare an anonymous class like the following code: As you can see, the syntax of an anonymous class is not named for it, but a direct new {} is finished. Externally, we have no way of knowing that this class is a dry horse, and we don't know how it works.   Copy code     var annoyCla1 = new    {        ID = 10010,      &NBS P Name = "Edisonchou",        age = 25   };     Console.WriteLine ("Id:{0}-name : {1}-age:{2} ", Annoycla1.id,annoycla1.name, annoycla1.age); The copy code is debugged, and we find that the anonymous class can achieve the effect of the named class completely:    1.2 Deep behind the anonymous class now that we have found that anonymous classes can fully implement the effect of a named class, we can be bold to guess that the compiler certainly internally helped us generate a class named class, so we explored it with the help of the Anti-compilation tool. By reflector, we found the compiler-generated anonymous class as shown in:   :  (1) The anonymous class is compiled and generates a [generic class] that can be seen in the <>f__ Anonymoustype0<<id>j__tpar, <name>j__tpar, <Age>j__TPar> is a generic class;  (2) the properties generated by the anonymous class are read-only, OKSee that the corresponding field is also read-only;    So, if we assign a value to a property in the program, then an error;    (3) shows that the anonymous class also overrides the three methods of the base class: Equals, GetHashCode and ToString; we can see how it is implemented for the ToString method we generated:    implementation of the effect as shown:    1.3 Anonymous class sharing you can imagine, If many anonymous classes are defined in our code, does the compiler generate a generic class for each anonymous class? The answer is no, the compiler takes it very far and avoids generating the type repeatedly. In other words, if you define multiple anonymous classes, you can share a generic class if certain conditions are met. Now, let's see what happens.:  (1) If the defined anonymous class is identical to the one previously defined: the property type and order are identical, the default share of the previous generic class   copy code             var annoyCla1 = new            {              &NBS P ID = 10010,                Name = "Edisonchou",                age = 25           };             C Onsole. WriteLine ("Id:{0}-name:{1}-age:{2}", annoycla1.id,                Annoycla1.name, Annoycla1.age);            CONSOLE.WRiteline (Annoycla1.tostring ());            //02. The attribute type and order are consistent with ANNOYCLA1, so a common use of an anonymous class & nbsp           var annoyCla2 = new                {  &nbs P                 ID = 10086,                    Name = "Wncudchou",                    age = 25  &NB Sp            };            Console.WriteLine ("Id:{0}-name:{1}-a Ge:{2} ", annoycla1.id,                Annoycla1.name, annoycla1.age);  &nbsp ;         Console.WriteLine ("Is the same Class of 1 and 2:{0}",                Annoycla1.gettype () = = Annoycla2.gettype ());     Copy the code through the last two lines of the above code: can we tell if it's a type? The answer is:true    (2If the property name and order are the same, but the attribute types are different, then a generic class is used together, but the generic parameter is changed, so different classes are generated at run time:  copy code             var ANNOYCLA3 = new                {              and nbsp     ID = "Edisonchou",                    Name = 10010,                    age = 25              &N Bsp };            Console.WriteLine ("Id:{0}-name:{1}-age:{2}", annoycla3.id,    & nbsp           Annoycla3.name, annoycla3.age);            Console.writel INE ("is the same Class of 2 and 3:{0}",                annoycla3.gettype () = = Anno Ycla2.gettype ()); Copy the code we just said that while the same generic class is shared, only the generic parameters change, so different classes are generated at run time. So, you can guess that the last two lines of code will show the result should be false, although they all use a generic class, but at run time generates two different classes.     (3) If the data type name and type are the same, but the order is different, then the compiler will recreate an anonymous class   copy code             var annoyCla4 = New&nbs P               {                    Na me = "Edisonchou",                    ID = 10010,      &N Bsp             age = 25               };            Console.WriteLine ("Id:{0}-name:{1}-age:{2}", annoycla4.id,                Annoycla4.name, annoycla4.age);            Console.WriteLine ("I s the same Class of 2 and 4:{0} ",                annoycla4.gettype () = = AnnoyCla2. GetType ()); Copy code run judgment result is:false    through reflector, it can be found that the compiler did regenerate a generic class:    two, anonymous methods   2.1 Speaking from the declaration of a delegate, the anonymous method in C # was introduced in c#2.0, which eventuallyThe only way to declare a delegate before c#2.0 is to use the age of a named method. But here's a look at how we declare a delegate before we have an anonymous method.    (1) First define a delegate type:  public delegate void DelegateTest (string testname); (2) Write a naming method that complies with the mandate:         public void TestFunc (string name)         {            Console.WriteLine ("Hello,{0}", name);       } (3) Finally declares a delegate instance: &nbs  p;    DelegateTest dgtest = new DelegateTest (TestFunc);    dgtest ("Edison Chou"); (4) Debug run can get the following output:    by the above step to see, we want to declare a delegate instance to write a compliant naming method. However, if the program is used only by this delegate, it will always feel that the code structure is a bit wasteful. As a result, Microsoft introduced anonymous methods, using anonymous methods to declare delegates, it will make the code structure concise, but also eliminate some of the cost of instantiation.  2.2 Introduction of anonymous Methods (1) First, let's take a look at the example above using anonymous methods:  delegatetest dgTest2 = new DelegateTest (delegate (string name) {       Console.WriteLine ("Good,{0}", name);});    from the running result graph, we can see that we have passed a method directly to the method name, this method is written in the format of Delegate (parameter) {method body}, and the content of the method body is written directly inside {}. So, we can not help cheering, but also to simplify some of the workload!   (2) Second, we will build the program through reflector to see how anonymous methods help us to achieve the effect of the naming method. &nbsp ① we can see that in compiling the generated class, in addition to our own definition of the method, there are more than two inexplicable members:    ② after one by one view, the original compiler helped us to generate a private delegate object and a private static method. We can boldly guess: The original anonymous method is not a method without a name, or generate a name method, but the name of the method is hidden, and the method name is generated by the compiler.      ③ through the above analysis, we still do not know, in the end, anonymous method delegate object in the program is how to embody? Here, we need to look at the main method, but through C # code we don't see a point that can help us understand. At this time, we want to root planing the bottom of a bit of trouble. Fortunately, under the expert guidance, we know can use IL (Intermediate code) to analyze. So, switch the display language in reflector, change C # to IL, and you'll see another world.     (3) from the above analysis, we can conclude that the compiler has done two things for the anonymous method, one is to generate a private static delegate object and a private static method, and the other is to put the address of the generated method into a delegate. The Invoke method that invokes the delegate object at run time executes the method held by the delegate object. Therefore, we can also see that anonymous methods need to be used in conjunction with delegates.  2.3 anonymous method Extension (1) anonymous method syntax sugar-more simplifies your code   in development, we tend to use syntactic sugars to write anonymous methods, such as the following:         DelegateTest DgTest3 = Delegate (string name)         {           console.  WriteLine ("goodbye,{0}", name);       };        DGTEST3 ("Edison Chou"); It can be seen that using this syntax sugar, the new DelegateTest () is also removed. As we can see, the compiler makes us more and more relaxed.   (2) There is also a brainiac-to pass an anonymous method into a method as a parameter  ① in development, we often declare a method whose parameters are aA delegate object that can accept any method that conforms to the delegate definition.      static void InvokeMethod (DelegateTest dg)     {        &NBSP;DG ("Edison C Hou ");   }② We can pass the defined method address as a parameter into the InvokeMethod method, for example: InvokeMethod (TestFunc); Of course, we can also use anonymous methods, and we can call the InvokeMethod method without having to define it separately.      InvokeMethod (delegate (string name)     {           Console.WriteLine ("Fuck,{0}", name);   }); (3) Omit ellipsis and omit-omit "curly brace"   after the compiler's continuous optimization, we found that even delegate behind the () can be omitted, we can look at the following section of code:     InvokeMethod ( Delegate {          console.writeline ("I love C sharp!");      }); And that's what we defined earlier.:         public delegate void DelegateTest (string testname);     & nbsp   static void InvokeMethod (DelegateTest DG)         {            DG ( "Edison Chou");       } We found that the method of definition is required to pass a string parameter, but we omit the parentheses after the DeletegateCount, then what is the result? After debugging, found that the result output is: I love C sharp!  at this time, we are a little baffled by the solution! Clearly there is no definition of parameters, why is it satisfied with the definition of the parameters of the contract? So, we take the problem or with the help of reflector to explore.  ① in the main function, you can see that the compiler automatically adds a method parameter that conforms to the DelegateTest delegate definition, which is a string of type strings. Although, the output is I love C sharp, but it does conform to the method definition, because it will accept a string parameter, although it is not used in the method body to use this parameter.    ② just saw the anonymous method in the main function, and now we can look at the naming method that the compiler generated for us.     extension Method  3.1 Magic-Initial Play extension method (1) referring to the extension method, I think most of the garden friends are not unfamiliar. But let's take a look at the MSDN definition: &NBSP;MSDN says: Extension methods enable you to "add" methods to existing types without creating new derived types, recompiling, or otherwise modifying the original types. The "add" here uses quotation marks because it does not really add a method to the specified type.   Then, sometimes we ask: why do we have to have an extension method? Here, we can think of as the name implies, expand the extension, then certainly involves the extensibility. In abstract Factory mode, we can switch to a new factory by adding a new factory class without changing the source code. This is also the case, without modifying the source code, the addition of a new method for a class, it also implements the extension of the class.   (2) Empty say no, let's see how the extension method is judged in C #: With smart hints, we find that there are some ways to take a pointer to the arrow below and see "tips" that we know he is an extension method. The result is that the where () method that we have been filtering on the collection is actually an extension method instead of a native one.     Let's take a look at the code example using where this extension method:  copy code         static void Useextensionmethod ()         {            list<person> Personlist = new list<person> ()             {              &N Bsp New Person () {id=1,name= ' Big Yellow ',age=10},                New person () {Id=2,nam E= "Little White",age=15},                New person () {id=3,name= ' middle Blue ', age =7}           };            ///Use the IEnumerable extension method below: W here            var datas = Personlist.where (delegate (person p)         & nbsp   {                return p.age >= 10;          & nbsp });             foreach (var data in datas)             {& nbsp               Console.WriteLine ("{0}-{1}-{2}",           &nbSp         data.id, data. Name, data. Age);           }       } Copy code the above code uses the where extension method to find the age>=10 data in the collection to form a new Data set and output:    (3) Since the extension method is to extend the class, can we do a custom extension? The answer is that it has to be. Let's take a look at how the extension method is defined, and you can see what the rules are by the Where method definition in the IEnumerable interface just now: by going to the definition, We can see that under the System.Linq namespace, there is a static class called Enumerable, whose member methods are all static methods, and most of the first parameters of each method begin with this. As a result, we can conclude that the three elements of the extension method are static classes, static methods, and the This keyword.      public static class enumerable    {        public static ienumerable< Tsource> union<tsource> (This ienumerable<tsource> first, ienumerable<tsource> second, Iequalitycomparer<tsource> comparer);   } Then the question comes again: why must it be static? We all know that static methods do not belong to instances of a class, that is, we do not need to instantiate this class, we can access this static method. So, you know.   (4) After reading the three elements of the extension method, we will automatically write an extension method:  copy code     public static class personextension    {  & nbsp     public static string Formatoutput P)         {            return string. Format ("id:{0},name:{1},age:{2}",                p.id, p.name, p.age);  &nbs P    }   } Copy the code above this extension method completes a string construct that formats the property information of the person object, and accomplishes the output in the above example. We can then change the code above to output:  copy code         static void Usemyextensionmethod ()       & nbsp {            list<person> personlist = new list<person> ()       &N Bsp     {                New person () {id=1,name= "Big Yellow",age=10},                New person () {id=2,name= ' Little white ',age=15},                New person () {id=3,name= "middle Blue",age=7}           };              var datas = Personlist.where (Delegate (PeRson p)             {                return p.age = 10;           });             foreach (var data in da TAS)             {              Console.WriteLine   (d) Ata. Formatoutput ());           }       }

. NET of those so-called new syntax Two: Anonymous class, anonymous method and extension method

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.