Check if Object is Dictionary or List

后端 未结 4 1070
逝去的感伤
逝去的感伤 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:01

    If you just need to detect the object is List/Dictionary or not, you can use myObject.GetType().IsGenericType && myObject is IEnumerable

    Here is some example:

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

提交回复
热议问题