如何编写和读取维度列表数组
本文关键字:列表 数组 读取 何编写 | 更新日期: 2023-09-27 18:24:19
我使用此代码写入数组
但是出现错误
void Start ()
{
List<int>[,] li = new List<int>[8,5];
li[0,0].Add(15); //error in here
Debug.Log(li[0,0][0]);
}
这是错误消息
NullReferenceException:对象引用未设置为对象的实例Word.Start()(位于Assets/Script/Word.cs:19)
我想使用列表和数组分配的对象,但我发现
li[0,0].Add(15);
一个错误,我做错了?
您应该创建一个List<int>
实例:
// create a list, add 15 to it and put the list into [0, 0] cell
li[0, 0] = new List<int>(){15};
由于List<int>[,] li = new List<int>[8,5];
只创建一个数组并用null
s填充它。您可以在循环中创建所有列表,然后安全地使用Add
:
List<int>[,] li = new List<int>[8,5];
for (int r = 0; r < li.GetLength(0); ++r)
for (int c = 0; c < li.GetLength(1); ++c)
li[r, c] = new List<int>();
li[0,0].Add(15);