Check if Object is Dictionary or List

后端 未结 4 1040
逝去的感伤
逝去的感伤 2020-12-30 01:02

Working with .NET 2 in mono, I\'m using a basic JSON library that returns nested string, object Dictionary and lists.

I\'m writing a mapper to map this

4条回答
  •  一整个雨季
    2020-12-30 01:49

    Use the is keyword and reflection.

    public bool IsList(object o)
    {
        if(o == null) return false;
        return o is IList &&
               o.GetType().IsGenericType &&
               o.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(List<>));
    }
    
    public bool IsDictionary(object o)
    {
        if(o == null) return false;
        return o is IDictionary &&
               o.GetType().IsGenericType &&
               o.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(Dictionary<,>));
    }
    

提交回复
热议问题