如何测试对象是否是数组/交错数组数组

本文关键字:数组 是否是 对象 何测试 测试 | 更新日期: 2023-09-27 18:35:45

我正在尝试测试对象是哪种数组:1D,2D或数组/交错数组。

这是我尝试过的:

    if (o is Array && ((Array)o).Rank == 2) {
        Console.Write ("2D-Array:  ");
    } 
    /* else if (o[0] is Array) {
        Console.WriteLine ("Jagged Array:  ");
    } */
    else if (o is Array) {
        Console.Write ("1D-Array:  ");
    } 

但是中间测试不起作用,因为Cannot apply indexing with [] to an expression of type 'object'

你还能怎么做?提前谢谢。

如何测试对象是否是数组/交错数组数组

由于

o是一个object并且您没有将其装箱为数组,因此此代码无法编译。这里有一个更简单的方法:

var arr = o as Array;
if(arr != null) 
{
    if(arr.Rank == 2) 
    {
        Console.Write ("2D-Array:  ");
    } 
    else if (arr.Length > 0 && arr.GetValue(0) is Array) 
    {
        Console.WriteLine ("Jagged Array:  ");
    } 
    else
    {
        Console.Write ("1D-Array:  ");
    }
}