How to check if a variable is Array or Object?

前端 未结 3 485
后悔当初
后悔当初 2021-01-11 14:24

For deserialising a json object, I had to define a parent class that would contain an object or an array of objects for the child class. It has to be an object if an object

3条回答
  •  心在旅途
    2021-01-11 15:10

    First off, an array is an object. That's a good thing, since it allows these functions to work (both assume using System;):

    bool IsArray(object o) { return o is Array; }
    bool IsArray(object o) { return o.GetType().IsArray; }
    

    Second, if you want a property whose type can be either X or X[], the property's type needs to be object:

    class Y             
    {
       private object _x;
       public object x {
           get { return _x; }
           set
           {
               if (value.GetType != typeof(X) && value.GetType != typeof(X[]))
                   throw new ArgumentException("value");
               _x = value;
           }
       }
    }
    

    This somewhat ignores the advantage of static typing, as you're using object and checking types at run time. It would really be much simpler to define the property as an array, even for those cases where there's only one value. In such cases, it would be an array whose length is 1.

提交回复
热议问题