Take a look at this super practical type of--anonymous type

Source: Internet
Author: User

In the original: Look at this super practical one type--anonymous type

Now that the anonymous type is super practical, you have to find a scene to persuade, if you have played PHP, there is a universal associative array of arrays, any of you in the associative array of arrays inside how to write, all

It is very convenient to use Json_encode to generate JSON.

<?php//You can write this .   $arr=Array("Name" = "HxC", "Age" =20, "ismale" =true); //you can write it like that.   $arrayName=Array("List" =Array(                                           Array("Name" = "John", "Age" = "a", "ismale" =true),Array("Name" = "Mary", "age" = "+", "ismale" =false),Array("Name" = "Jackson", "age" = "+", "ismale" =true)                                        ), "TotalCount" =>100); $json=json_encode ($arr); Echo $json;?>

In the case of C #, when we want to output JSON to the foreground, we have to define an entity, give the entity various assignments, and then serialize the output to the foreground as JSON, like this:

1      Public class Program2     {3         Staticvoid Main (string[] args)4         {5             varJSON =NewStudent () {Name = "john", age = +, Ismale =true };6 7JavaScriptSerializer js =NewJavaScriptSerializer ();8 9             varr = JS.Serialize(JSON);Ten}

Since the new anonymous type was added in. NETFramework 3.5, everything has changed.

One: Looking for a scene

<1> Scenario 1:

Sometimes we want to output JSON to the foreground, but this JSON is a very simple state json, just like this {"status": "1", "message": "Commit succeeded"}, but I have to do it in the past

Define a state class first, then serialize it, just like this.

1      Public class Program2     {3         Staticvoid Main (string[] args)4         {5             varJSON =NewStatus () {status = "1", message = "Commit succeeded" };6 7JavaScriptSerializer js =NewJavaScriptSerializer ();8 9             varresult = JS.Serialize(JSON);Ten  OneConsole.WriteLine (result); A  -Console.Read (); -         } the  -          Public classStatus -         { -              Public stringstatus {get; set;} +  -              Public stringmessage {get; set;} +         } A}

What happens if we use anonymous types?

1         Staticvoid Main (string[] args)2         {3             varJSON =New{status = "1", message = "Commit succeeded" };4 5JavaScriptSerializer js =NewJavaScriptSerializer ();6 7             varresult = JS.Serialize(JSON);8 9Console.WriteLine (result);Ten  OneConsole.Read (); A}

From the context of the code, really let us write a lot less code, but also improve our development efficiency, with this anonymous type, we can also like a PHP array, arbitrary definition

Simple or complex structure, then serialized into JSON.

<2> Scenario 2:

There is also a frequently used scenario is that when we get the list data, often in the form of paging, such as a page is 20 data, but for the front page convenient paging, the backend must be passed a

A totalcout parameter, so that the front end knows Pagecount=math.ceil (Totalcount/pagesize), calculates the total number of pages, in the traditional way, we need to re-packaging on the bottom list

A class, and then add a TotalCount property to the class, just like this.

1     ///<summary>2     ///Collection Packing class3     ///</summary>4      Public classStudentpage5     {6          Public List<Student>List{get; set;}7          Publicint total {get; set;}8     }9     ///<summary>Ten     ///Student Entity class One     ///</summary> A      Public classStudent -     { -          Public stringName {get; set;} the  -          Publicint Age {get; set;} -  -          Publicbool Ismale {get; set;} +}

With the anonymous type, we don't have to write anymore, it should look like this.

1      Public class Program2     {3         Staticvoid Main (string[] args)4         {5             var List=New List<Student>()6             {7                   NewStudent () {name= "John", Age=25, ismale=true},8                   NewStudent () {name= "Mary", Age=24, ismale=false},9                   NewStudent () {name= "Jackson", age=30,ismale=true}Ten             }; One  A             //Core points -             varJSON =New{List=List, TotalCount = 20 }; -  theJavaScriptSerializer js =NewJavaScriptSerializer (); -  -             varresult = JS.Serialize(JSON); -  +Console.WriteLine (result); -  +Console.Read (); A         } at     } -  -      Public classStudent -     { -          Public stringName {get; set;} -  in          Publicint Age {get; set;} -  to          Publicbool Ismale {get; set;} +}

Is it a nice feeling to see this JSON? Yes, indeed in our development is very practical, then the question came, so practical things, where the principle of its can be learned?

II: Fundamentals

Now that you want to learn, let's dissect the IL code and see what this thing has done. For ease of understanding, I define a very simple anonymous class.

1 var New {Name = "Jackson", age = 20};

And then we'll see what's going on in IL.

Do not look at Il Fortunately, a look is really startled, on a word of things, become il after there are so many of the stuff ... and the class name obtained is also very wonderful, opening incredibly have <> this angle bracket, when

The reason for this is simply to avoid conflicts between the class name we define and the auto-generated one, and the compiler does not allow the class name to start with <>, although it is allowed at the CLR level, okay,

We went down and we found out from IL.

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 there is no set_name and set_age method, which means that the property is a read-only property.

Finally we found that the anonymous type also overrides the Equals,gethashcode and ToString methods, and here I just look at the Equals method.

As you can see, IL code becomes very ugly and confusing when there are generic parameters in the type, but several key instructions can be found, after overriding the Equals method of object,

The method of comparing equality in an anonymous type is compared by one-by-one, which is similar to the way a value type is compared, since the following two anonymous objects should be equal.

This is unthinkable in reference types.

But interestingly, when we look at the IL code again, we find that we have not generated two anonymous classes, but JSON and Json2 common an anonymous class, the benefit is to reduce the IL instruction volume,

It can be said that the compiler is also very intelligent, to optimize the resources to the best.

Well, the general principle is that, if you're smart enough, you'll find the ^_^ for the project scenario.

Take a look at this super practical type of--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.