检查对象是字典还是列表

检查对象是字典还是列表

本文介绍了检查对象是字典还是列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在单声道中使用.NET 2,我使用基本的使用 is 关键字和反射。

  public bool IsList(object o)
{
if(o == null)return false;
return o是IList&&
o.GetType()。IsGenericType&&
o.GetType()。GetGenericTypeDefinition()。IsAssignableFrom(typeof(List>));

$ b $ public bool IsDictionary(object o)
{
if(o == null)return false;
return o是IDictionary&&
o.GetType()。IsGenericType&&
o.GetType()。GetGenericTypeDefinition()。IsAssignableFrom(typeof(Dictionary<>));
}


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 to a jsonData class that I already have and I need to be able to determine if the underlying type of an object is a Dictionary or a List. Below is the method I'm using to perform this test, but was wondering if theres a cleaner way?

private static bool IsDictionary(object o) {
    try {
        Dictionary<string, object> dict = (Dictionary<string, object>)o;
        return true;
    } catch {
        return false;
    }
}

private static bool IsList(object o) {
    try {
        List<object> list = (List<object>)o;
        return true;
    } catch {
        return false;
    }
}

The library I'm using is litJson but the JsonMapper class essentially doesn't work on iOS, hence the reason I am writing my own mapper.

解决方案

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

这篇关于检查对象是字典还是列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:33