如何分配给锯齿状数组? [英] How to assign to a jagged array?
问题描述
我正在写一个简短的程序,最终将播放连接四。
I am writing a short program which will eventually play connect four.
有一部分不起作用。我在第16行声明了一个锯齿状的数组。
There is one part which isn't working. I have a jagged array declared on line 16:
char[][] board = Enumerable.Repeat(Enumerable.Repeat('-', 7).ToArray(), 7).ToArray();
我认为这样:
-------
-------
-------
-------
-------
-------
-------
执行此操作时 board [5] [2] ='*'
我得到
--*----
--*----
--*----
--*----
--*----
--*----
--*----
而不是我想要的:
-------
-------
-------
-------
-------
--*----
-------
目前如何运行(输出中应该只有一个星号):
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
将创建一个序列包含一个重复值。因此,您将创建一个char [] [],其中每个数组都指向相同的引用。在这种情况下,当您更改一个数组时,您将全部更改。
Enumerable.Repeat
will create a sequence that contains one repeated value. So you will create an char[][] in which every array will point to same reference. In this case when you change one of the arrays you will change all of them.
您需要以这种方式创建锯齿状数组,array [5] [2]将仅更改第5个数组:
You need to create the jagged array this way and array[5][2] will only change the 5th array :
char[][] array = Enumerable.Range(0, 7).Select(i => Enumerable.Repeat('-', 7).ToArray()).ToArray();
array[5][2] = '*';
这篇关于如何分配给锯齿状数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!