检查对象是否是字典或列表

use*_*383 15 c# generics mono json

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

我正在编写一个mapper来将它映射到我已经拥有的jsonData类,我需要能够确定a的基础类型object是Dictionary还是List.下面是我用来执行此测试的方法,但是想知道这是否更干净?

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用的库是,litJsonJsonMapper该类基本上不适用于iOS,因此我正在编写自己的映射器.

Dus*_*gen 40

使用is关键字和反射.

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<,>));
}
Run Code Online (Sandbox Code Playgroud)

  • @shieldgenerator7,您需要使用 System.Collections 命名空间中的非通用接口“IList”。 (3认同)
  • 如果您想将对象转换为 [`(value as IEnumerable&lt;object&gt;).Cast&lt;object&gt;().ToList()`](/sf/answers/1130353661/)可用类型 (2认同)

svi*_*ick 5

如果要检查某个对象是否属于某种类型,请使用is运算符。例如:

private static bool IsDictionary(object o)
{
    return o is Dictionary<string, object>;
}
Run Code Online (Sandbox Code Playgroud)

尽管对于这么简单的事情,您可能不需要单独的方法,只需is在需要的地方直接使用运算符即可。