Transferring a list of a list to a 2D array

2019-09-08 07:17发布

问题:

Ok, so i'm trying to get a 2D array to serialize in an xml file and then be able to load it. The main part works but I have found (possibly false) that you can't use a 2d array in the content pipeline readers and writers. I have replaced the 2d array with a List<List<string>> but I still need the data as a 2d array. This is what I have so far but it throws an null reference exception:

TILArray = new string[Width, Height];// I do initialize the array

for (int x = 0; x < Width; x++)
{
    for (int y = 0; y < Height; y++)
    {
        if (TILList[x][y] != null)
        {
            Tiles[x, y] = Content.Load<Tile>(TILList[x][y]);
            TILArray[x, y] = TILList[x][y];// This line throws the exception
        }
    }
}

Should it be giving me a null reference exception if I'm trying to assign to it? Also if anyone knows how to use 2d arrays directly in the content pipeline reader and writer i'd appreciate it

Edit: The exception:

An unhandled exception of type 'System.NullReferenceException' occurred in TileEngine.dll

Additional information: Object reference not set to an instance of an object.

Edit: Well I've kept testing it and it seems that it only throws the exception when it's in the loop. When I try to set TILArray[0,0] outside the loop it works fine, but in the loop it doesn't work and throws the exception.

Edit: WOW, I just found that if I move the line that throws the exception above this line:

Tiles[x, y] = Content.Load<Tile>(TILList[x][y]);

It says the exception was thrown in the line that contains only a }!

EDIT: I've done some more tests and have found that THE PROBLEM IS NOT WITH COPYING TO THE ARRAY. when I comment out the line that threw the exception it still throws it! Is there anything that would cause the game to throw a NullReference exception from a line where there isn't even any code?

回答1:

Have considered an array of arrays? Instead of TILArray[,], you'd use TILArray[][] which, like your list, is an array of arrays. The serialiser should be able to handle this.