问题
I am writing a short program which will eventually play connect four.
Here it is so far, pastebin
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();
Which I think looks like this:
-------
-------
-------
-------
-------
-------
-------
when I do this board[5][2] = '*'
I get
--*----
--*----
--*----
--*----
--*----
--*----
--*----
instead of what I'd like:
-------
-------
-------
-------
-------
--*----
-------
How it runs at the moment (output should only have one asterisk):
回答1:
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. 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.
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] = '*';
来源:https://stackoverflow.com/questions/40644966/how-to-assign-to-a-jagged-array