C# multidimensional arrays iteration

只愿长相守 提交于 2021-02-12 04:14:10

问题


I'm new to C# and looking at arrays.

Given:

int[][] myJagArray = new int[5][];

Why does the following print the types of j (System.Int32[]), and not each j's contents?

foreach (int[] j in myJagArray)
{
    Console.WriteLine("j : {0}",j);
}

回答1:


Because Array.ToString() does not return the contents of the array, it returns the type name, and Console.WriteLine implicitly calls ToString() on each object you send it as a parameter.

This has no regard to the fact that the array is part of a multi-dimensional array, it is simply the way the CLR developers chose to (or rather, chose not to) implement ToString() on System.Array.




回答2:


It prints the output from ToString() method, since j, in this case, is an array, it use Object ToString implementation, and that behavior is printing its type.

Here what you may want to do:

foreach (int[] j in myJagArray)
{
    StringBuilder sb = new StringBuilder("j : ");

    foreach (int k in j)
    {
        sb.append("[").append(k).append("]");
    }

    Console.WriteLine(sb.Tostring());
}



回答3:


You're printing out an array of int.

Try the following to print the first value within the array:

Console.WriteLine("j : {0}",j[0]);

To print out the entire contents you may want to try the following:

foreach (int[] j in myJagArray)
{
    foreach (int i in j)
    {
        Console.WriteLine("i : {0}",i);
    }
}



回答4:


You should do like below

for(int i=0;i<5;i++)
    for( int j=0;j<5;j++)
        print(myjagarray[i][j].tostring());



回答5:


When you output a value using Console.WriteLine you are actually first calling ToString() on that value, and Array.ToString() doesn't return the values, but the type. If you want to output the values of j you need to run a second loop:

foreach (int[] j in myJagArray)
{
    Console.Write("j: ");
    foreach (int i in j)
    {
        Console.Write("{0} ",i);
    }    
    Console.Write("\n");
}


来源:https://stackoverflow.com/questions/14757664/c-sharp-multidimensional-arrays-iteration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!