C # Implementation of object dictionary Conversion,

Source: Internet
Author: User

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 ;}}}
   
  
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.