. NET one of those so-called new grammars: auto-attributes, implicit types, named arguments, and automatic initializers

Source: Internet
Author: User
Tags reflector

Opening: In the daily. NET development learning, we tend to come into contact with some of the newer syntax, compared to the old syntax, they made a lot of improvements, simplifying a lot of complex code format, but also greatly reduced the number of our novice code farmers. But, in addition to being happy, we are curious about what the compiler has done for us. So, we use the anti-compilation artifact, to see what the compiler has done! In fact, many of this article is not a new grammar, for many people may have been in contact for a long time, here is mainly aimed at. NET old version, is a "relative" of the new syntax.

/ * NEW Syntax Index * /
1. Automatic attributes auto-implemented Properties 2. Implicit type var 3. Parameter default value and named Parameter 4. Object initializer and collection initializer {} 5. Anonymous classes & anonymous methods 6. Extension methods 7. System built-in delegate func/action 8.Lambda-expression 9. Standard query operator Operator 10.LINQ query Expressions
I. Automatic attribute Quest 1.1 Previous practices: Write private variables first, and then write public properties
     Public classStudent {PrivateInt32 _id;  PublicInt32 Id {Get{return_id;} Set{_id =value;} }        Private string_name;  Public stringName {Get{return_name;} Set{_name =value;} }        PrivateInt16 _age;  PublicInt16 Age {Get{return_age;} Set{_age =value;} }    }
1.2 Current practice: Declaring an empty property
     Public class person    {        publicgetset;}          Public string Get Set ; }          Public Get Set ; }    }

PS: Now it seems, is not a lot less code? Directly declaring an empty property, the compiler can help us to complete the previous Private member fields and get, set methods, so we can go through the Reflector Anti-compilation tool to see, exactly how to complete this operation.

1.3 Great "village base"-CSC (C sharp Compiler): C # compiler

PS: Why this refers to the village base, one is because the rural base abbreviation is CSC, two is because I prefer to eat rural-based Chinese fast food, so, click! (It feels like a country-based advertising, but I still like the country-based, of course, the price is thrown aside)

(1) First we compile the above small program, and then drag the compiled Exe/dll to the anti-compilation artifact Reflector(or ilspy is like the DA)

(2) To find the person class, you can see the compiled result: CSC helps us automatically generate private fields corresponding to common attributes

As we can see, the automatically generated fields have some differences from the previous fields:

① adds a [compilergenerated] feature above each field (Attribute), as the name implies: it is generated by the compiler;

② the variable name for each field is in a certain format, such as <age>k__backingfield, you can see that the format is:< property name >k_backingfield ; (Backingfield as the name implies is the field behind)

(3) After reading the auto-generated fields, let's see how the properties are defined:

① and auto-generated fields, attributes are also added to the [compilergenerated] feature to differentiate

② well-known, the property is a get and a set of two methods of encapsulation, then we wrote the empty Get/set method is how to be compiled generated?

As a result, we can see that in the Get and set methods, the [compilergenerated] feature is added to the difference, and we automatically correspond to the auto-generated private field, which is the private field that we wrote manually. The method of common attributes remains consistent. So, the automatic attribute is a useful syntactic sugar that helps us do two things: Automatically generate private fields and automatically match private fields in the Get/set method.

Second, implicit type-keyword: var2.1 still hold the pipa half cover-can you guess who I am?

Previously, we needed to explicitly indicate which type it was when defining each variable. However, when we have Var, everything becomes so harmonious that we can define all types with a var.

    var  - ;      Max ;     var "" ;     " Edisonchou " ;    Console.WriteLine ("age={0}", age);    Console.WriteLine ("name={0}", name);

Click Debug, find the compiler automatically help us match the correct type and display it successfully:

So, we're curious to see if the compiler actually recognizes the specified type, so we'll look at it again with the Anti-compilation tool:

It can be seen that our lovely CSC correctly helped us to infer the correct type, can't help but want to give it a few 32 praise!

However, the variable type cannot be changed because the type was determined at the time of the Declaration, such as when we gave the variable a different type from the definition in the code we just made, an error occurs.

2.2 Good knives for the blade-implicit type Application scenario

In data-based business development, we make LINQ queries against a collection of data, and the result of this LINQ query may be an object of type objectquery<> or iqueryable<>. Therefore, in the case of ambiguous target type, we can use Var key to declare:

List<userinfo> userlist = roleservice.loadroles (param); var  from inch userlist            where 0           Select u;
2.3 But "love" is restraint-implicit type usage restrictions

(1) The declared variable is a local variable , not a static or instance field;

(2) The variable must be initialized at the same time as the declaration, and the compiler will infer the type based on the initialization value;

(3) Initialization is not an anonymous function , and the initialization expression cannot be null;

(4) A variable is declared only once in the statement and cannot be changed after declaration (see the example above)

(5) The data type of the assignment must be a type that can be determined at compile time ;

Iii. parameter defaults and named Parameters 3.1 methods with default values
        Static voidMain (string[] args) {            //01. Parameter function with default valueFuncwithdefaultpara (); //02. Omit a default parameter callFuncwithdefaultpara (10086);        Console.readkey (); }        Static voidFuncwithdefaultpara (intID =10010,BOOLGender =true) {Console.WriteLine ("Id:{0},gender:{1}", ID, gender?"Mans":"Woman"); }

Click Debug to display the results as follows:

3.2 Post-compilation method calls

Again, in order to explore the details of the method invocation with the parameter default value, we use the anti-compilation artifact to see the occult:

(1) First, let's look at how the method with the default value parameter is compiled:

As you can see, a large number of Attribute -based development methods are used in the. NET framework, where the attribute Defaultparametervaluethat represents the default value is added to the parameter.

(2) Second, take a look at how the invocation process in the main function is compiled:

  

As you can see, the compiler helps us populate the default values in parentheses of the method invocation. Here, we can not help but wonder if in the call, do not specify the ID (that is, using the ID default value of 10010), and just specify gender to false whether the compile pass? Let's try it out:

        Static void Main (string[] args)        {            ///  01. Parameter function             Funcwithdefaultpara () with default value;             //  02. Omit a default parameter call            Funcwithdefaultpara (10086);             // Error Call:            Funcwithdefaultpara (false);            Console.readkey ();        }

At this point, the following error occurred:

Therefore, we know that CSC is not so intelligent, unable to understand our advanced "intentions." So, there is a way to solve this demand, so the naming parameters were born.

3.3 Using named parameters

Named parameters are introduced for method calls in the new syntax, in the form of parameter names: argument values

        Static voidMain (string[] args) {            //01. Parameter function with default valueFuncwithdefaultpara (); //02. Omit a default parameter callFuncwithdefaultpara (10086); //Error Call://Funcwithdefaultpara (FALSE); //03. Invoking with named argumentsFuncwithdefaultpara (Gender:false);        Console.readkey (); }    

By debugging, you can get the following results:

From the previous analysis, we can analyze whether the invocation of the specified parameter value will be generated after the use of the named parameter is compiled:

Iv. Automatic initializer 4.1 property initializer

(1) In development, we often set the properties of these objects for new:

        Static void Initialpropertyfunc ()        {            new" Xiao Qiang "  );            Console.WriteLine ("name:{0}-age:{1}", P.name, p.age);        }    

(2) However, after compiling we found that the original is the same way: first new out, and then a property of a property to assign a value . Here, the compiler first generates a temporary object g_initlocal0, then assigns a value to its property, and finally passes the address of the object g_initlocal0 to the object p to be used.

4.2 Set of initializers

(1) In development, we often initialize it in the instantiation of a collection:

        Static voidInitialcollectionfunc () {List<Person> personlist =NewList<person>()            {                NewPerson () {name="Xiao Qiang", age=Ten},                NewPerson () {name="Xiao Wang", age= the},                NewPerson () {name="Xiao Li", age= -}            }; foreach(Person personinchpersonlist) {Console.WriteLine ("Name:{0}-age:{1}", person. Name, person.            Age); }        }

(2) through the above set initializer we know that the compiler will still be compiled into the original way, that is, the new out, after allocating memory space for it, and then one by one to assign a value to its properties. Well, in the initialization of the collection we can also boldly guess, the compiler has done the above optimization work: First, each object new out, then one by one to assign a value to the property, and finally call the collection's Add method to add it to the collection. So, we are still anti-compilation, a look at:

Accessories download

(1) REFLECTOR:HTTP://PAN.BAIDU.COM/S/1EVCJG of anti-compilation artifact

(2) The so-called New grammar Demo:http://pan.baidu.com/s/1ntwqdat

Zhou Xurong

Source: http://www.cnblogs.com/edisonchou/

The copyright of this article is owned by the author and the blog Park, welcome reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to give the original link.

. NET one of those so-called new grammars: auto-attributes, implicit types, named arguments, and automatic initializers

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.