Check if Object is Dictionary or List

后端 未结 4 1071
逝去的感伤
逝去的感伤 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 02:07

    Modifying the above answer. In order to use GetGenericTypeDefinition() you must preface the method with GetType(). If you look at MSDN this is how GetGenericTypeDefinition() is accessed:

    public virtual Type GetGenericTypeDefinition()
    

    Here is the link: https://msdn.microsoft.com/en-us/library/system.type.getgenerictypedefinition(v=vs.110).aspx

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

提交回复
热议问题