Let's take a look at this super practical type-Anonymous type

Source: Internet
Author: User

Since the anonymous type is super practical, you have to find a scenario to convince us that if you have been using PHP, there are 10 thousand associated array arrays in it. How can you write in the associated array, both

JSON can be generated using json_encode, which is very convenient.

<? PHP // you can write $ arr = array ("name" => "hxc", "Age" = 20, "ismale" => true) like this ); // You can also write $ arrayname = array ("list" => array (Array ("name" => "John", "Age" => "20 ", "ismale" => true), array ("name" => "Mary", "Age" => "24", "ismale" => false ), array ("name" => "Jackson", "Age" => "30", "ismale" => true), "totalcount" => 100 ); $ JSON = json_encode ($ ARR); echo $ JSON;?>


When C # is used, when we want to output JSON to the foreground, we must first define an object, assign values to various entities, and then serialize the object to the foreground in the form of JSON, for example:


 1     public class Program 2     { 3         static void Main(string[] args) 4         { 5             var json = new Student() { Name = "john", Age = 25, IsMale = true }; 6  7             JavaScriptSerializer js = new JavaScriptSerializer(); 8  9             var r = js.Serialize(json);10     }


Since the anonymous type is added in. netframework 3.5, everything has changed.


I. Scenario search

<1> scenario 1:

Sometimes we want to output JSON to the foreground, but this JSON is a very simple status JSON, like this {"status": "1", "message ": "submitted successfully"}, but in the past, I had to do it myself.

First define a status class and then serialize it, as shown below.

1 public class Program 2 {3 static void main (string [] ARGs) 4 {5 var JSON = new status () {status = "1 ", message = "submitted"}; 6 7 javascriptserializer JS = new javascriptserializer (); 8 9 var result = Js. serialize (JSON); 10 11 console. writeline (result); 12 13 console. read (); 14} 15 16 public class status17 {18 Public String status {Get; set;} 19 20 Public String message {Get; Set ;}21} 22}


Let's see what happens if we use the anonymous type?

1 static void main (string [] ARGs) 2 {3 var JSON = new {status = "1", message = "submitted successfully "}; 4 5. javascriptserializer JS = new javascriptserializer (); 6 7 var result = Js. serialize (JSON); 8 9 console. writeline (result); 10 11 console. read (); 12}

From the perspective of the amount of context code, we do not write much code, which improves our development efficiency. With this anonymous type, we can also be like the PHP array, what you want

A simple or complex structure is serialized as JSON.


<2> Scenario 2:

Another frequently used scenario is that when we obtain list data, we often use the form of pagination. For example, if one page contains 20 pieces of data, but for the convenience of paging at the front end, the backend must pass

Totalcout parameters. In this way, the front-end will know pagecount = math. Ceil (totalcount/pagesize) and calculate the total number of pages. In the traditional method, we need to package on the underlying list.

A class, and then add a totalcount attribute to the class, as shown below.

1 /// <summary> 2 /// set packaging Class 3 /// </Summary> 4 public class studentpage 5 {6 public list <student> List {Get; set ;} 7 public int total {Get; set ;} 8} 9 // <summary> 10 // student object class 11 /// </Summary> 12 public class student13 {14 public string name {Get; set ;} 15 16 public int age {Get; set;} 17 18 public bool ismale {Get; set;} 19}


With the anonymous type, we no longer need to write it like below.


1 public class Program 2 {3 static void main (string [] ARGs) 4 {5 var list = new list <student> () 6 {7 new student () {name = "John", age = 25, ismale = true}, 8 new student () {name = "Mary", age = 24, ismale = false }, 9 new student () {name = "Jackson", age = 30, ismale = true} 10}; 11 12 // core point 13 var JSON = new {list = List, totalcount = 20}; 14 15 response criptserializer JS = new response criptserializer (); 16 17 var result = Js. serialize (JSON); 18 19 console. writeline (result); 20 21 console. read (); 22} 23} 24 25 public class student26 {27 public string name {Get; set;} 28 29 public int age {Get; set ;} 30 31 public bool ismale {Get; set;} 32}


Is there a great feeling when I see this JSON? Yes, it is very practical in our development. The question is, where can we learn the principle of this practical thing?


Ii. Basic Principles

If you want to learn it, let's analyze its il code to see what it has done? For ease of understanding, I define a very simple Anonymous class.

1 var json = new { Name = "jackson", Age = 20 };


Then let's see what happened in Il?


I don't think it's okay to look at Il. I was shocked at first glance. There were so many things after I turned it into Il... And the class name acquisition is also very strange, the beginning is actually the <> such angle brackets, when

The reason for writing this is very simple, that is, to avoid conflicts between the class names we define and automatically generated. Besides, the compiler does not allow class names starting with <>, although it is allowed at the CLR level, well,

We continue to go down to the bottom. from Il, we also found

Two template parameters: <age> J _ TPAR and <Name> J _ TPAR.

Two fields: <age> I _ field and <Name> I _ field.

Two attribute Methods: get_name and get_age. Here we find that the set_name and set_age methods are not available, which means this attribute is a read-only attribute.


Finally, we also found that the anonymous type also overwrites the equals, gethashcode, and tostring methods. Here I will only look at the equals method.



As you can see, when there are generic parameters in the type, the Il code becomes very ugly and confusing, but several key commands can be found. After rewriting the equals method of the object,

The method for comparing equal values in the anonymous type is to compare fields one by one, which is similar to the value type comparison method, the following two anonymous objects should be equal.

This is unimaginable in the reference type.


However, it is interesting to look at the Il code and find that there are not two anonymous classes, but the JSON and json2 share an anonymous class. The advantage is that the Il instruction volume is reduced,

It can be said that the compiler is still very intelligent and can optimize resources to the best.


Well, the general principle is like this. If you are smart enough, you will find the appropriate project scenario ^_^.


Let's take a look at this super practical type-Anonymous type

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.