[英]How to assign to a jagged array?
I am writing a short program which will eventually play connect four. 我正在写一个简短的程序,最终将连接四个。
Here it is so far, pastebin 到目前为止,它是pastebin
There is one part which isn't working. 有一部分不起作用。 I have a jagged array declared on line 16: 我在第16行声明了一个锯齿状数组:
char[][] board = Enumerable.Repeat(Enumerable.Repeat('-', 7).ToArray(), 7).ToArray();
Which I think looks like this: 我认为这看起来像这样:
-------
-------
-------
-------
-------
-------
-------
when I do this board[5][2] = '*'
I get 当我这样做时board[5][2] = '*'
我得到了
--*----
--*----
--*----
--*----
--*----
--*----
--*----
instead of what I'd like: 而不是我想要的:
-------
-------
-------
-------
-------
--*----
-------
How it runs at the moment (output should only have one asterisk): 它如何运行(输出应该只有一个星号):
You are creating your jagged array in wrong way ! 你正在以错误的方式创建你的锯齿状阵列!
char[][] board = Enumerable.Repeat(Enumerable.Repeat('-', 7).ToArray(), 7).ToArray();
Enumerable.Repeat
will create a sequence that contains one repeated value. Enumerable.Repeat
将创建一个包含一个重复值的序列。 So you will create an char[][] in which every array will point to same reference. 因此,您将创建一个char [] [],其中每个数组都将指向相同的引用。 In this case when you change one of the arrays you will change all of them. 在这种情况下,当您更改其中一个阵列时,您将更改所有阵列。
You need to create the jagged array this way and array[5][2] will only change the 5th array : 你需要以这种方式创建锯齿状数组,数组[5] [2]只会改变第5个数组:
char[][] array = Enumerable.Range(0, 7).Select(i => Enumerable.Repeat('-', 7).ToArray()).ToArray();
array[5][2] = '*';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.