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

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

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

 private static bool IsDictionary(object o) { try { Dictionary dict = (Dictionary)o; return true; } catch { return false; } } private static bool IsList(object o) { try { List list = (List)o; return true; } catch { return false; } } 

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

使用is关键字和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<,>)); } 

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

 private static bool IsDictionary(object o) { return o is Dictionary; } 

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

修改上面的答案。 要使用GetGenericTypeDefinition() ,必须在方法前加上GetType() 。 如果你看一下MSDN,这就是GetGenericTypeDefinition()的访问方式:

 public virtual Type GetGenericTypeDefinition() 

这是链接: 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<>)); } 

如果您只需要检测对象是否为List/Dictionary ,则可以使用myObject.GetType().IsGenericType && myObject is IEnumerable

这是一些例子:

 var lst = new List(); var dic = new Dictionary(); string s = "Hello!"; object obj1 = new { Id = 10 }; object obj2 = null; // True Console.Write(lst.GetType().IsGenericType && lst is IEnumerable); // True Console.Write(dic.GetType().IsGenericType && dic is IEnumerable); // False Console.Write(s.GetType().IsGenericType && s is IEnumerable); // False Console.Write(obj1.GetType().IsGenericType && obj1 is IEnumerable); // NullReferenceException: Object reference not set to an instance of // an object, so you need to check for null cases too Console.Write(obj2.GetType().IsGenericType && obj2 is IEnumerable);