C # Implementation of object dictionary Conversion,
C # convert objects to dictionaries
When I learned how to develop C #, I encountered the need to convert the object into a dictionary. Here I will record it for later viewing.
Using System; using System. collections. generic; using System. linq; using System. reflection; using System. text; using System. threading. tasks; namespace Application {class MapUtils {////// Convert an object to a dictionary //////Object To be converted ///Whether to ignore NULL. Here, I do not need to convert the NULL value. If it is normal to use, it can be completely converted by default without passing the parameter ///
Public static Dictionary
ObjectToMap (object obj, bool isIgnoreNull = false) {Dictionary
Map = new Dictionary
(); Type t = obj. getType (); // obtain the class corresponding to the object. The corresponding type is PropertyInfo [] pi = t. getProperties (BindingFlags. public | BindingFlags. instance); // obtain the current type public attribute foreach (PropertyInfo p in pi) {MethodInfo m = p. getGetMethod (); if (m! = Null & m. IsPublic) {// process NULL if (m. Invoke (obj, new object [] {})! = Null |! IsIgnoreNull) {map. add (p. name, m. invoke (obj, new object [] {}); // Add an element to the dictionary }}return map ;}}}