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