检查对象是字典还是列表 [英] Check if Object is Dictionary or List

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

问题描述

在单声道中使用.NET 2,我使用基本的 JSON 库来返回嵌套的字符串,对象字典和列表。



我正在编写一个映射器将其映射到我已有的jsonData类,并且我需要能够确定对象的基础类型是一个字典或一个列表。下面是我用来执行这个测试的方法,但是想知道这是一种更简洁的方式吗?

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



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


我使用的库是 litJson 但是 JsonMapper 类本质上不适用于iOS,因此我正在编写我自己的映射器。

解决方案使用 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<,>));
}

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆