声明数组的锯齿状数组

时间:2017-03-15 16:53:21

标签: c# arrays jagged-arrays

我搜索过,无法在C#中找到解决方案

我已经声明并分配了数组:

string[] arr1 = {"a","b","c","d","e","f"};
string[] arr2 = {"1","2","3","4","5","6"};
string[] arr3 = {"s","t","a","c","k","o"};
string[] arr4 = {"v","e","r","f","l","w"};

我想从这些数组中创建一个锯齿状数组,但没有成功。

string[,] port = new string[]
{
    new string[] arr1[],
    new string[] arr2[],
    new string[] arr3[],
    new string[] arr4[],
};

我犯的错误在哪里?

我的程序将生成随机int来调用锯齿状数组中的值

Random random = new Random();
int x = random.Next(0,5);
int y = random.Next(0,3);
Console.WriteLine(port[y,x]);

2 个答案:

答案 0 :(得分:1)

有两个错误:

  1. 您不会声明锯齿状数组,而是声明多维数组。由于您的“内部”数组已经定义,因此您需要一个数组数组,这称为“锯齿状”数组。
  2. 您已经声明了内部数组
  3. ,因此声明中不需要new string[]

    所以这应该有效:

    string[][] port = new string[][]
    {
        arr1, arr2, arr3, arr4
    };
    

    或者使用数组初始化程序更短:

    string[][] port = { arr1, arr2, arr3, arr4 };
    

    要访问此阵列,请使用以下命令:

    Console.WriteLine(port[y][x]);
    

答案 1 :(得分:1)

试试这个:

string[] arr1 = { "a", "b", "c", "d", "e", "f" };
string[] arr2 = { "1", "2", "3", "4", "5", "6" };
string[] arr3 = { "s", "t", "a", "c", "k", "o" };
string[] arr4 = { "v", "e", "r", "f", "l", "w" };

string[][] port = new string[4][];
port[0] = arr1;
port[1] = arr2;
port[2] = arr3;
port[3] = arr4;

或者简单地说:

string[][] port = new string[][] { arr1, arr2, arr3, arr4 };

用法:

string test = port[1][5];