C # Review notes (4)--c#3: Innovating the Way you write code (using intelligent compilers to make mistakes)

Source: Internet
Author: User

using an intelligent compiler to prevent errors

The main content of this chapter:

    • Auto-Implemented properties: Write simple attributes that are directly supported by the field and no longer look bloated;
    • Implicitly-typed Local variables: Simplify the declaration of local variables by inferring types based on initial values;
    • Object and Collection initializers: You can create and initialize objects with an expression;
    • Implicitly typed arrays: simplifies the creation of arrays by inferring the types of arrays based on content;
    • Anonymous type: Allows the creation of new temporary types to contain simple attributes;
Auto-implemented Properties

This feature is simple I don't want to describe, but in order to maintain the integrity of the content, put a picture:

Like an anonymous method and an iterator, it generates a fallback field with the help of the compiler.

The auto-implemented properties are common to both assignment and value methods, but you can also continue to use the C#2 private assignment method.

When implementing your own structure (struct), all constructors must explicitly call the parameterless constructor, so that the compiler knows that all the fields are definitely assigned. Because there is a type of initialization order:

The order in which classes or structs are executed at initialization, followed by the following:

1: Sub-class static variables

2: Sub-class static constructors

3: Sub-class non-static variables

4: Parent class static variable

5: Parent class static constructor

6: Non-static variable of parent class

7: Parent class constructor

8: Sub-class constructors

You can see that everything except the constructor is initialized by itself in the initialization base class.

implicitly-typed local variables

The first thing you need to illustrate is that implicit types can only be used for local variables and not for field variables.

2nd, C # is still a static language, but requires the compiler to infer the type of the variable for you, which is still type static at compile time.

Declare an implicitly-typed local variable with the var keyword .

Small summary: You can use implicit types for all variables in all cases, but only in the following cases:

    • The declared variable is a local variable, not a static field and an instance field;
    • The variable is initialized at the same time as the Declaration;
    • The initialization expression is not a method group, nor is it an anonymous function (if you do not force type conversions);
    • An initialization expression is not null;
    • Only one variable is declared in the statement;
    • The type you want the variable to have is the compile-time type of the initialization expression;
    • The initialization expression does not contain the variable being declared.

implicit types of local variable also have some bad places, sometimes you have to carefully judge its type. For example:

    • var a = 2147483647;
    • var B = 2147483648;
    • var c = 4294967295;
    • var d = 4294967296;
    • var e = 9223372036854775807;
    • var f = 9223372036854775808;

The class of these variables above is not good to judge in the first time. However, sometimes you have to use, such as to return an anonymous type, can only write: var a=new {name= "Pangjianxin", age=10}; What type of expression do you want to use for reference?

Simplified initialization

directly on the code.

 Public classPerson { Public stringName {Get; }  Public intAge {Get;Set; }  PublicList<person> Persons {Get; } =NewList<person>();  PublicLocation Location {Get; } =NewLocation ();  PublicPerson () {} PublicPerson (stringname) {             This. Name =name; }    }     Public classLocation { Public stringCity {Get;Set; }  Public stringStreet {Get;Set; } }

The above defines two classes, a person class, and a location class. The person class maintains two automatic attributes name and age, and also maintains two read-only properties persons and location. There is also an argument-free constructor and a constructor with parameters.

As already mentioned, the class executes the constructor after the static and non-static fields are initialized, and the property is essentially a pair of get/set methods, and there is no initialization.

Take a look at the invocation situation:

 static  void  Main (string  [] args) {person P  = new  person ("  pangianxin   " ) {Age  = 18   = {City =  baotou   ", Street = "  gangtiedajie   ""            Span style= "COLOR: #000000" >}};            Console.WriteLine (p.location.city); P.location=new location (); The location could not be initialized because he is read-only. 

p.location.city = "Baotou";
P.location.street = "Gangtiedajie";

            Console.readkey ();        }

The object initializer is used above to initialize the object.

The first thing to notice is P. Location is a read-only property. We can't directly assign a property, but we can assign it after the reference to the property, in the C # language specification, this is called "setting an embedded object's properties". is to set properties for the property. There is no limit to this.

The 2nd is location = {City = "Baotou", Street = "Gangtiedajie"}. The compiler discovers another object initializer to the right of the equal sign, so the property is appropriately applied to the embedded object.

Collection Initialization Program

var names = new List {"Holly", "Jon", "Tom", "Robin", "William"};

That's it.

Also, the compiler calls the Add method in the background to add the element to the collection.

The collection initializer must adhere to the following two points:

    • Implement Ienumerale
    • With the Add method

For the 1th, it is reasonable to require the implementation of IEnumerable, because the compiler must know that it is a collection of meanings. For the 2nd, because the compiler calls the Add method in the background to hold the element, the set you initialize must be guaranteed to have this Add method.

implicitly-typed arrays

String[] names = {"Holly", "Jon", "Tom", "Robin", "William"};

This approach looks concise, but it is not possible to pass the contents of the curly braces directly to the method: MyMethod ({"Holly", "Jon", "Tom", "Robin", "William"}); To do this: MyMethod (new string[] {"Holly", "Jon", "Tom", "Robin", "William"});

Anonymous type

This thing is the focus of today.

Anonymous types are more useful when combined with more advanced features.

The type of initialization with this thing can only be undertaken with Var: var myinfo=new {name= "Pangjianxin", age=19}; Other than object.

If two anonymous object initializers contain the same number of attributes, and they have the same name and type, and appear in the same order, they are considered to be of the same type.

Static voidMain (string[] args) {            varPersons =New[]            {                New{Name="pangjianxin", Age= +                },                New{Name="pangjianxin", Age= +                },                New{Name="pangjianxin", Age= +                },                New{Name="pangjianxin", Age= +                },                New{Name="pangjianxin", Age= +                }            };        Console.readkey (); }    

If the type of anonymous type above is inconsistent, for example, the order of one of the attributes is reversed, an additional attribute is added, and so on, the compiler will error: "The best type of an implicitly typed array cannot be found."

The compiler generates a generic type for anonymous types in the background to help the anonymous type initialize, and the generic class is placed in a separate assembly. It generates the class name in the background super pervert:

It takes the type name and age of the anonymous type as the type parameter of the generic type, and then the main method becomes this:

Compiler's bad, huh?

Return to see what members of an anonymous type have:

First it was inherited object. Nonsense

It has a fallback field and a read-only property

There is a constructor that gets all the initial values.

The Equals, GetHashCode, ToString of object are overridden

Since all properties are read-only, the anonymous type is immutable as long as these properties are not immutable. This provides you with all the general advantages of the "not easy to change" feature-the ability to pass values to the method without fear of changing them, sharing data between threads, and so on.

Projection Initialization Program

var person = new {name = ' pangjianxin ', age = 19};
var Anotherperson = new {name = Person.name, Isadult = (Person.age > 18)};

Anotherperson uses the attributes of person to form a new anonymous type. This is the projection initialization program.

However, the greatest use of anonymous types is in LINQ. Using a Select or SelectMany operation, you can narrow down the range you are looking for.

C # Review notes (4)--c#3: Innovating the Way you write code (with intelligent compilers to make mistakes)

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.