声明数组的锯齿状数组
Jagged array by declared 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
s 以调用锯齿状数组中的值
Random random = new Random();
int x = random.Next(0,5);
int y = random.Next(0,3);
Console.WriteLine(port[y,x]);
有两个错误:
- 您声明的不是 锯齿状 数组,而是 多维 数组。由于您的 "inner" 数组已经定义,因此您需要一个 数组的数组 ,称为 "jagged" 数组。
- 您不需要在声明中使用
new string[]
,因为您已经声明了内部数组
所以这应该有效:
string[][] port = new string[][]
{
arr1, arr2, arr3, arr4
};
或者使用更短的数组初始值设定项:
string[][] port = { arr1, arr2, arr3, arr4 };
要访问此数组,请使用:
Console.WriteLine(port[y][x]);
试试这个:
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];
我在 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
s 以调用锯齿状数组中的值
Random random = new Random();
int x = random.Next(0,5);
int y = random.Next(0,3);
Console.WriteLine(port[y,x]);
有两个错误:
- 您声明的不是 锯齿状 数组,而是 多维 数组。由于您的 "inner" 数组已经定义,因此您需要一个 数组的数组 ,称为 "jagged" 数组。
- 您不需要在声明中使用
new string[]
,因为您已经声明了内部数组
所以这应该有效:
string[][] port = new string[][]
{
arr1, arr2, arr3, arr4
};
或者使用更短的数组初始值设定项:
string[][] port = { arr1, arr2, arr3, arr4 };
要访问此数组,请使用:
Console.WriteLine(port[y][x]);
试试这个:
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];