C # Anonymous objects Add dynamic properties

Source: Internet
Author: User

A requirement is encountered during the development process, which requires dynamic creation of objects and their dynamic properties. After trying several methods, finally completed the requirements, record the process, for the reference of the park friends

1. Dynamically create object one: Anonymous objects

Object New "Jin Chao Qian", age="to", Birthday =datetime.now};

To create an anonymous object:

Issue 1: Unable to dynamically map object properties

Workaround: Get an Object value using reflection

Object New " Jin Chao Qian ", age=", Birthday =DateTime.Now}; Response.Write (string. Format ("name:{0}", Obj1. GetType (). GetProperty ("Name"null). ToString ()));

Output results

Issue 2: Unable to dynamically create object properties

2. Using dynamic object creation method two, dynamic object

Dynamic New  " Jin Chao qian "= DateTime.Now; Response.Write (string. Format ("name:{0}", Obj2. Name));

To create a dynamic object:

Output Result:

Problem: You can't add objects dynamically

3. Dynamically creating objects and their properties

Looking at the definition of expandoobject, it is found that the essence is a dictionary store key value pairs, whether the method can be used to dynamically manipulate the object properties?

dictionary<string,Object> temp =Newdictionary<string,Object>(); temp. ADD ("Name","Jin Chao Qian"); temp[" Age"] = to; temp["Birthday"] =DateTime.Now;Dynamicobj =NewSystem.Dynamic.ExpandoObject ();foreach(keyvaluepair<string,Object> Iteminchtemp) {(IDictionary<string,Object>) (obj). ADD (item. Key, item. Value);} Response.Write (string. Format ("name:{0}"Obj. GetType (). GetProperty ("name"). GetValue (obj,NULL). ToString ()));

Object view:

Output:

Output is an error, can not get object properties with reflection, the object's field and property are all null, then we use dictionary as above to output

Finally fix the work, have similar needs of friends can refer to.

C # Anonymous objects Add dynamic properties

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.