[英]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.