C # Dynamic types and anonymous classes

Source: Internet
Author: User

Dynamic type
Simple example

Dynamic New // dynamic type fields are readable and writable 1  "Test"; string json = Utils.ConvertJson.JsonEncode (expando);  // Output {id:1,name: ' Test '}

Adding fields dynamically

list<string> FieldList =Newlist<string> () {"Name"," Age","Sex"};//From config or dbDynamicDobj =NewSystem.Dynamic.ExpandoObject ();varDIC = (idictionary<string,Object>) Dobj;foreach(varFielditeminchFieldList) {Dic[fielditem]="Set"+fielditem+"value";/*realize the function of dynamic adding property like js var obj={};                                                                        var field= "Id"; Eval ("obj."                                                                        +field+ "= 1"); Alert (obj. ID); 1*/}varval = dobj. Name;//"Set Name value"varVal1=dobj. Age;//"Set age value"

Enumerates all members of the object

foreach(varFielditeminch(Idictionary<string, object>) {dobj) {varv = (Fielditem.key +": "+fielditem.value);} Anonymous class//var aaaa = new {id=1,name= "Test"};//anonymous class fields are read-only and not writableDynamicAAAA =New{id=1, name="Test"};//anonymous class fields are read-only and not writableAaaa. Id =2;//non-writable error cannot be a property or indexer "<>F__ANONYMOUSTYPE1<INT>. Id "Assignment-it is read-only Dynamicobj = Newtonsoft.Json.JsonConvert.DeserializeObject ("{Name: ' AA ', Sex: ' Male ', age:11}");varname = obj. Name.value;//AA

C # Dynamic types and anonymous classes

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.