如何测试二维数组的边界以避免索引自动失效异常(C#)

如何测试二维数组的边界以避免索引自动失效异常(C#),c#,multidimensional-array,indexoutofboundsexception,C#,Multidimensional Array,Indexoutofboundsexception,处理一维数组非常简单。但我们如何避免在每行长度不同的二维数组(锯齿数组)中测试超出范围的位置 这是我的代码(如果有人想测试): static void Main(字符串[]args) { 对象[][]x=weirdReturn(); int k=0; while(x[0][k]!=null)//此代码生成异常 { 对于(int i=0;i

处理一维数组非常简单。但我们如何避免在每行长度不同的二维数组(锯齿数组)中测试超出范围的位置

这是我的代码(如果有人想测试):

static void Main(字符串[]args)
{
对象[][]x=weirdReturn();
int k=0;
while(x[0][k]!=null)//此代码生成异常
{
对于(int i=0;i
这没有什么神奇之处-只需检查长度,避免索引超出该值减去1,就像一维数组一样

你的代码看起来很混乱,你只是想这样循环数组吗

static void Main(string[] args)
{
    object[][] x = weirdReturn();

    for (int i = 0; i < x.Length; i++)
    {
        for (int j = 0; j < x[i].Length; j++)
        {
            Console.Write("{0} ", x[i][j]);
        }
        Console.WriteLine("");
    }
}


static object[][] weirdReturn()
{
    DateTime d = new DateTime();
    d = DateTime.Now;
    object[] a2 = { 'X', 1.79, d, 100 };
    object[] a1 = { 0, 'a', "objectX" };
    object[][] retVal = new object[2][];
    retVal[0] = a1;
    retVal[1] = a2;
    return retVal;
}
static void Main(字符串[]args)
{
对象[][]x=weirdReturn();
对于(int i=0;i
你的循环完全是胡说八道。你想干什么?我应该把问题描述得更清楚。。最初我想把它放到一个已有的线程中。我想在交错数组中迭代。一种矩阵,但行的长度不同。问题是我不容易找到有多少行。我知道在这个例子中有2个,但为了更灵活,我想概括一下这个问题。行数是外部数组的长度,可以通过调用
x.Length
x.Length在这个例子中是3,这是a1的长度。这就是问题所在,我需要矩阵中的行数,在本例中是2。我知道代码很凌乱,这就是我不知道如何找出错误的原因,
x.Length
根据上述古怪返回方法的定义返回2
static void Main(string[] args)
{
    object[][] x = weirdReturn();

    for (int i = 0; i < x.Length; i++)
    {
        for (int j = 0; j < x[i].Length; j++)
        {
            Console.Write("{0} ", x[i][j]);
        }
        Console.WriteLine("");
    }
}


static object[][] weirdReturn()
{
    DateTime d = new DateTime();
    d = DateTime.Now;
    object[] a2 = { 'X', 1.79, d, 100 };
    object[] a1 = { 0, 'a', "objectX" };
    object[][] retVal = new object[2][];
    retVal[0] = a1;
    retVal[1] = a2;
    return retVal;
}