How to convert object to Dictionary in C#?

前端 未结 15 1753
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 17:58

How do I convert a dynamic object to a Dictionary in C# What can I do?

public static void MyMethod(object obj)
{
    if (typ         


        
15条回答
  •  眼角桃花
    2020-12-13 18:29

    I use this helper:

    public static class ObjectToDictionaryHelper
    {
        public static IDictionary ToDictionary(this object source)
        {
            return source.ToDictionary();
        }
    
        public static IDictionary ToDictionary(this object source)
        {
            if (source == null)
                ThrowExceptionWhenSourceArgumentIsNull();
    
            var dictionary = new Dictionary();
            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
                AddPropertyToDictionary(property, source, dictionary);
            return dictionary;
        }
    
        private static void AddPropertyToDictionary(PropertyDescriptor property, object source, Dictionary dictionary)
        {
            object value = property.GetValue(source);
            if (IsOfType(value))
                dictionary.Add(property.Name, (T)value);
        }
    
        private static bool IsOfType(object value)
        {
            return value is T;
        }
    
        private static void ThrowExceptionWhenSourceArgumentIsNull()
        {
            throw new ArgumentNullException("source", "Unable to convert object to a dictionary. The source object is null.");
        }
    }
    
    
    

    the usage is just to call .ToDictionary() on an object

    Hope it helps.

    提交回复
    热议问题