If object is of type dictionary, return directly
If object is a NameValueCollection type, it is added to dictionary
If object is a Hashtable type, add it to dictionary
... Other key value types please improve yourself
If object is not of the above type, it is converted to the dictionary type in the Il language.
The specific code is as follows:
Public Staticdictionary<string,Object> Convertfromobject (Objectobj) { if(obj isdictionary<string,Object>) return(dictionary<string,Object>) obj; varNVC = obj asNameValueCollection; if(NVC! =NULL) {Dictionary<string,Object> dict =Newdictionary<string,Object>(stringcomparer.ordinalignorecase); foreach(stringKeyinchNVC. Keys) Dict. ADD (Key, Nvc[key]); returndict; } varHS = obj asHashtable; if(HS! =NULL) {Dictionary<string,Object> dict =Newdictionary<string,Object>(stringcomparer.ordinalignorecase); foreach(stringKeyinchHs. keys.oftype<string>()) Dict. ADD (Key, Hs[key]); returndict; }
varType =obj. GetType (); Lock(dictionarycache) {Func<Object, dictionary<string,Object>>getter; if(Dictionarycache.trygetvalue (Type, outGetter) = =false) {getter=createdictionarygenerator (type); Dictionarycache[type]=getter; } varDict =getter (obj); returndict; } }
Private Staticfunc<Object, dictionary<string,Object>>createdictionarygenerator (Type type) {varDM =NewDynamicMethod ((string. Format ("dictionary{0}", Guid.NewGuid ())),typeof(dictionary<string,Object>),New[] {typeof(Object)}, type,true); ILGenerator il=DM. GetILGenerator (); Il. DeclareLocal (typeof(dictionary<string,Object>)); Il. Emit (OPCODES.NOP); //dictionary<string, object> dic = new dictionary<string, object> ();Il. Emit (Opcodes.newobj,typeof(dictionary<string,Object>). GetConstructor (type.emptytypes)); Il. Emit (OPCODES.STLOC_0); foreach(varIteminchType. GetProperties (BindingFlags.Public |bindingflags.instance)) {stringColumnName =item. Name; Il. Emit (OPCODES.NOP); Il. Emit (OPCODES.LDLOC_0); Il. Emit (Opcodes.ldstr, columnName); Il. Emit (OPCODES.LDARG_0); Il. Emit (Opcodes.callvirt, item. Getgetmethod ()); if(item. Propertytype.isvaluetype) {IL. Emit (Opcodes.box, item. PropertyType); } il. Emit (Opcodes.callvirt,typeof(dictionary<string,Object>). GetMethod ("ADD")); } il. Emit (OPCODES.NOP); Il. Emit (OPCODES.LDLOC_0); Il. Emit (Opcodes.ret); varFunc = (func<Object, dictionary<string,Object>>) DM. CreateDelegate (typeof(func<Object, dictionary<string,Object>>)); returnfunc; }
Convert object to Dictionary method