简体   繁体   中英

2 dimensional array in C#

第二个维度可以初始化为动态大小吗?

否(因为C#数组维度是固定的),但您可以创建List<T>的数组。

You mean a jagged array? Like this:

class Program
{
  public int[][] jaggedArray = {
                                 new int[]{ 1 } ,
                                 new int[]{} ,
                                 new int[]{ 1 , 2 , 3 } ,
                               } ;
}

Normally a jagged array has a size. You could use two collections:

List<List<int>> list = new List<List<int>>();

You can access the values the same way you would access any array. The advantage is that you don't need to specify the size at creation.

Edit: if the "outer" array is fixed, you could use:

List<int>[] list = new List<int>[100]();

Edit: looking to your example I'd say something like this could do the trick:

List<int>[] sVertRange = new List<int>[924];

int nH = 0;
for (int h = 315; h < 1240; h++) 
{
    for (int v = 211; v <= 660; v++) 
    {
            Color c = bmp.GetPixel(h, v);
            if (c.R > 220 && c.G < 153) 
        {
            if(sVertRange[nH] == null)
            {
                sVertRange[nH] = new List<int>();
            }

                    sVertRange[nH].Add(v);
            }
            nH++;
        }
}

if you want to create 2 dimensional array in C# each element type is bitmap

int num1 = 10,num2 = 20;
Bitmap[][] matrix= new Bitmap[num1][]; 
for (int i = 0; i < num1; i++ )
     matrix[i] = new Bitmap[num2];

UPDATE : I just tested this and it doesn't work--it crashes immediately. So how is the following written in Kees's syntax?

    int[][] sVertRange = {new int[924] ,new int[]{}};  
    int nH = 0;
    int nV = 0;
    for (int h = 315; h < 1240; h++) {
        for (int v = 211; v <= 660; v++) {
            Color c = bmp.GetPixel(h, v);
            if (c.R > 220 && c.G < 153) {
                sVertRange[nH][nV++] = v;
            }
        nH++;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM