如何检查变量是数组还是对象? [英] How to check if a variable is Array or Object?

查看:32
本文介绍了如何检查变量是数组还是对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了反序列化一个 json 对象,我必须定义一个父类,它包含一个对象或子类的对象数组.如果检索到对象,则必须是对象,如果从 json 检索数组,则必须是对象数组.

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 was retrieved, or an array of objects if an array was retrieved from the json.

JSON 数组对象

{"y":{"x":[{"data":28}, {"data":56}, {"data":89}]}}

JSON 对象

{"y":{"x":{"data":28}}}

y 一次接收 x,另一次接收 x[].没有这样的条件来确定 y 将接收一个数组还是一个对象.

y is receiving x at a time, and x[] at another time. There is no such condition to determine whether y would recieve an array or an object.

因此,为了确定我是否收到数组,我正在检查 IsArray() 条件.

Hence for determining whether I received an array or not, I am checking the IsArray() condition.

我试过了

class Y
{
   public X x { get { return System.IsArray() ? new X() : new x[] }; set; }
}

class X
{
   public int data { get; set; }
}

  1. 它不起作用.
  2. System.IsArray() 未被识别??

推荐答案

首先,数组一个对象.这是一件好事,因为它允许这些函数工作(都假设 using System;):

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

其次,如果你想要一个属性的类型可以是X或者X[],那么属性的类型需要是object:

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

这在某种程度上忽略了静态类型的优势,因为您正在使用 object 并在运行时检查类型.将属性定义为数组确实要简单得多,即使对于只有一个值的情况也是如此.在这种情况下,它将是一个长度为 1 的数组.

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.

这篇关于如何检查变量是数组还是对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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