c# - Mapping object to dictionary and vice versa -


are there elegant quick way map object dictionary , vice versa?

example:

idictionary<string,object> = new dictionary<string,object>(); a["id"]=1; a["name"]="ahmad"; // ..... 

becomes

someclass b = new someclass(); b.id=1; b.name="ahmad"; // .......... 

using reflection , generics in 2 methods extensions can achieve that.

right, others did same solution, uses less reflection more performance-wise , way more readable:

public static class objectextensions {     public static t toobject<t>(this idictionary<string, object> source)         t : class, new()     {             t someobject = new t();             type someobjecttype = someobject.gettype();              foreach (keyvaluepair<string, object> item in source)             {                 someobjecttype.getproperty(item.key).setvalue(someobject, item.value, null);             }              return someobject;     }      public static idictionary<string, object> asdictionary(this object source, bindingflags bindingattr = bindingflags.declaredonly | bindingflags.public | bindingflags.instance)     {         return source.gettype().getproperties(bindingattr).todictionary         (             propinfo => propinfo.name,             propinfo => propinfo.getvalue(source, null)         );      } }  class {     public string prop1     {         get;         set;     }      public int prop2     {         get;         set;     } }  class program {     static void main(string[] args)     {         dictionary<string, object> dictionary = new dictionary<string, object>();         dictionary.add("prop1", "hello world!");         dictionary.add("prop2", 3893);         someobject = dictionary.toobject<a>();          idictionary<string, object> objectbacktodictionary = someobject.asdictionary();     } } 

Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -