[英]Storing Lists Inside An Array
是否可以在数组内部存储包含列表的类?
我对这个概念有些麻烦。
这是我的代码:
我的班级称为“ 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>();
}
}
这是我的数组的定义,名为“ tileItems”:
public static arrayItems[, ,] tileItems;
这是我创建数组的方法:
Program.tileItems = new arrayItems[Program.newMapWidth, Program.newMapHeight, Program.newMapLayers];
我面临的问题是数组的内容为空。 我收到此错误:
Object reference not set to an instance of an object.
当我尝试通过Add()命令在数组内填充列表时,我得到了相同的错误。
你能指导我正确的方向吗? 提前致谢。
您需要初始化数组中的每个列表:
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();
}
}
}
第一。
您正在创建arrayItems
数组,该数组是引用类型,因为您将其定义为类。 因此,在初始化数组时,默认情况下,所有元素都将分配为null
。 这就是为什么您得到错误。 您必须初始化数组的每个元素。
由于您已经在类定义中初始化了列表,因此arrayItems
在循环内重新初始化arrayItems
的list属性。
您有一个包含一堆指向任何东西的指针的数组。 因此,您实际上首先需要在每个数组元素中初始化一个新的arrayItems
。
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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.