Understand implicit type, object initialization program, and anonymous type

Source: Internet
Author: User

Understand implicit type, object initialization program, and anonymous type
In C #3.0, almost every new feature is provided for the LINQ service. Therefore, this article will introduce the following new features introduced in C #3.0: the locally variable objects of the automatically implemented property implicit type and the array anonymous type of the Set initialization program implicit type are actually easy to understand. For these features, the compiler helps us do more (think about anonymous methods and iterator blocks) to simplify our code. The automatically implemented attributes are before C #3.0. When we define the attributes, the following code is generally used: public class Book {private int _ id; private string _ title; public int Id {get {return _ id;} set {_ id = value ;}} public string Title {get {return _ title ;} set {_ title = value ;}} introduced the automatically implemented attribute in C #3.0. the compiler will help us perform more conversions, so we can convert the above implementation code to: public class Book {public int Id {get; set;} public string Title {get; set ;}} after the automatically implemented attributes are used, the Code becomes shorter and we do not need to define private fields. In fact, after checking the IL code, we will find that the compiler defines private fields for us and implements the get/set method. Note: when using the structure, if you want to use automatic attributes, there will be a small problem: All constructors need to explicitly call the non-parameter constructor this (), only in this way can the compiler know that all fields are explicitly assigned values. For example, in the following code, when we delete ": this ()", the compiler reports an error. Public struct Student {public int Id {get; set;} public string Name {get; set;} public string Gender {get; set ;} // when using automatic attributes in the structure, you must explicitly call the non-parameter constructor this () public Student (string name): this () {this. name = name ;}} implicit type local variables C #1.0 and C #2.0 are static, displayed, and secure. In C #3.0, we can use the var keyword to define variables of the implicit type, but the variables are still static, but the compiler can help us deduce the type of variables. Let's take a look at the code below. The use of implicit statements is the same as the IL code of the commented-out statements: static void Main (string [] args) {var str = "hello world "; // string str = "hello world"; var num = 9; // int num = 9; Console. writeLine (str. getType (); Console. writeLine (num. getType (); Console. read ();} through the code output, we can see that each implicit type variable is static (we can also view the type of implicit type variables through single-step debugging ), here, the compiler will help us to deduce the type. To verify this, but when we assign an integer value to the str variable, an error "Cannot implicitly convert type 'int' to 'string'" is returned. Static void Main (string [] args) {var str = "hello world"; // string str = "hello world"; str = 9; Console. read ();} some restrictions apply when the implicit type is used. Not all variables can use the implicit type: the declared variable is a local variable, it cannot be a static field or an instance field variable. When declaring a variable, it must be initialized. the compiler must deduce the type of the variable based on the value of the variable, otherwise, an error occurs during compilation. The initialization expression cannot be a method group or an anonymous function (without forced type conversion) var enter = delegate {Console. writeLine () ;}; // compilation error var enter = (Action) delegate {Console. writeLine () ;}; // normal, because the compiler can deduce the type. The initialization expression is not null. It is implicitly converted to any reference type or null type. Therefore, the compiler cannot declare only one variable in a type inference statement. "var a = 2, B = 3; "the advantages and disadvantages of implicit types of compilation errors may be obtained. Sometimes, using implicit types can reduce the code length. Without affecting code readability, we focus on more useful Code. However, sometimes the implicit type is less readable. Therefore, you need to determine when to use implicit variables. The following is a simple example static void Main (string [] args) {// simplifies the code without sacrificing readability var wordCount = new Dictionary <string, int> (); foreach (var dict in wordCount) {Console. writeLine ("number of {0} is {1}", dict. key, dict. value);} // The variable type var numA = 2147483647; var numB = 2147483648; var numC = 4294967295; Console. writeLine (numA. getType (); Console. writeLine (numB. getType (); Console. writeLine (numC. getType (); Console. Read ();} implicit type local variable objects and set initialization programs in C #3.0, we have a new object and set initialization method. Object initializers when we have an object initialization program, the object initialization code becomes more intuitive and simple. Take an example: public class Book {public int Id {get; set;} public string Title {get; set;} // if no default constructor exists, public Book () {} public Book (string title) {this. title = title ;}} class Program {static void Main (string [] args) {// C # method of Initializing an object before 3.0 Book b1 = new Book (); b1.Id = 1; b1.Title = "C # step by step"; // use the object initialization program Book b2 = new Book () {Id = 2, title = "C # in depth"}; Book b3 = new Book {Id = 3, Title = "C # in depth"}; Book b4 = new Book ("C # in depth") {Id = 1 };}} when we check the IL code, we will find that the IL code of b1, b2 and b3 is exactly the same. Collection initializers is also proposed in C #3.0 to initialize the collection list. We can easily implement the initialization of the collection. Next, in the example above, we can create a Book List: // C #3.0, the method List for initializing the set <Book> bookList1 = new List <Book> (); bookList1.Add (b1 ); bookList1.Add (b2); bookList1.Add (b3); bookList1.Add (b4); // use the set initialization program List <Book> bookList2 = new List <Book> {b1, b2, b3, b4 }; List <Book> bookList3 = new List <Book> {new Book {Id = 5, Title = "Java in depth"}, new Book {Id = 6, title = "Python in depth" },}; you can see that the Code becomes more concise after the set initialization list is used. By viewing the IL code, we can find that when using the set to initialize the List, the compiler actually helped us call the Add method of List to Add elements. Implicit arrays are in C #1.0 and C #2.0. When using arrays, you must specify the specific array types involved. In C #3.0, you can use "new []" to declare and initialize an implicit array. Let's take a simple example: string [] names = {"Wilber", "Will", "July"}; PrintName (names ); printName (new string [] {"Wilber", "Will"}); // uses an anonymous array in C #3.0, the compiler is responsible for inferring the array type PrintName (new [] {"Wilber", "Will"}); var nameArray = new [] {"Wilber", "Will ", "July"}; PrintName (nameArray); // The type cannot be inferred. The Compiler reports an error // var array = new [] {1, "hello world "};...... Private static void PrintName (string [] names) {foreach (var name in names) {Console. writeLine (name) ;}} anonymous type before C #3.0, when we create an object, we need a type. In C #3.0, the concept of the anonymous type (similar to the anonymous method, the compiler has done a lot of work for us) is introduced. We can use the new keyword to define attributes for the object, and assign values to these attributes. Let's look at an example: static void Main (string [] args) {// create an anonymous object // assign a value to the attribute through the anonymous object initialization program var student = new {Name = "Wilber ", age = 28, Gender = "Male"}; Console. writeLine ("{0} is {1} years old", student. name, student. age); // use an implicit array to initialize the list var school = new [] {// use the same anonymous type to create an instance new {Name = "Wilber ", gender = "Male", Age = 28}, new {Name = "Will", Gender = "Male", Age = 27}, new {Name = "Lily ", gender = "Female", Age = 26 },}; int totalAge = 0; foreach (var stu in school) {totalAge + = stu. age;} Console. writeLine (totalAge); Console. read ();}

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.