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

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

问题描述

为了反序列化一个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. System.IsArray()无法识别


推荐答案

p>首先,数组一个对象。这是一件好事,因为它允许这些函数工作(两个假设使用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.

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

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