简体   繁体   中英

Storing Lists Inside An Array

Is it possible to store a Class that contains a List inside an array?

I am having some trouble with this concept.

Here's my code:

My Class Called "arrayItems":

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EngineTest
{
    [Serializable] //List olarak save etmemiz için bu gerekli.
    public class arrayItems
    {
        public List<items> items = new List<items>();
    }
}

Here's the definition of my Array called "tileItems":

 public static arrayItems[, ,] tileItems;

Here's how I create my Array:

    Program.tileItems = new arrayItems[Program.newMapWidth, Program.newMapHeight, Program.newMapLayers];

The problem I am facing is that the content of my Array is null. And I am getting this error:

Object reference not set to an instance of an object.

When I try to populate the List inside the array by Add() command I get the same error.

Can you direct me to the right direction please? Thanks in advance.

You need to initialise each list within the array:

for (int i = 0; i < newMapWidth; i++)
{
    for (int j = 0; j < newMapHeight; j++)
    {
        for (int k = 0; k < newMapLayers; k++)
        {
            arrayItems[i,j,k] = new arrayItems();
        }
    }
}

first.

You are creating and array of arrayItems , which is a reference type, because you defined it as a class. So when you initialize your array, all elements will be assigned null by default. That's why you get the error. You have to initialize each element of your array.

Since you are already initializing the list within the class definition you do not need to re-initialize the list property of arrayItems within the loop.

You have an array that has a bunch of pointers that point to nothing. So you actually need to instiante a new arrayItems in each array element first.

for (int i = 0; i < newMapWidth; i++)
{
    for (int j = 0; j < newMapHeight; j++)
    {
        for (int k = 0; k < newMapLayers; k++)
        {
            arrayItems[i,j,k]= new arrayitem();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM