C # Add dynamic attributes to anonymous objects,
An object and its dynamic attributes need to be dynamically created during the development process. After trying several methods, I finally completed the requirement, recorded the process, and gave them a reference.
1. dynamically create object 1: anonymous object
Object obj1 = new {Name = "Jin Chao Qian", Age = "31", Birthday = DateTime. Now };
The created anonymous object:
Problem 1: The object attributes cannot be dynamically mapped.
Solution: Get object values using reflection
Object obj1 = new {Name = "Jin Chao Qian", Age = "31", Birthday = DateTime. now}; Response. write (string. format ("Name: {0}", obj1.GetType (). getProperty ("Name "). getValue (obj1, null ). toString ()));
Output result
Problem 2: Unable to dynamically create Object Attributes
2. Create dynamic objects method 2. Dynamic Objects
Dynamic obj2 = new System. dynamic. expandoObject (); obj2.Name = "Jin Chao Qian"; obj2.Age = 31; obj2.Birthday = DateTime. now; Response. write (string. format ("Name: {0}", obj2.Name ));
Dynamic object created:
Output result:
Problem: still cannot add objects dynamically
3. dynamically create objects and their attributes
Dictionary <string, object> temp = new Dictionary <string, object> (); temp. add ("Name", "Jin Chao Qian"); temp ["Age"] = 31; temp ["Birthday"] = DateTime. now; dynamic obj = new System. dynamic. expandoObject (); foreach (KeyValuePair <string, object> item in temp) {(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:
The output is incorrect and the Object Attributes cannot be obtained using reflection. After investigation, all the fields and properties of this object are null, so we use Dictionary for output as above.
Finally, the job is closed. If you have similar needs, please refer to it.