【问题标题】:Storing Lists Inside An Array在数组中存储列表
【发布时间】:2012-07-03 13:49:47
【问题描述】:

是否可以将包含 List 的 Class 存储在数组中?

我在这个概念上遇到了一些麻烦。

这是我的代码:

我的班级叫做“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() 命令填充数组中的列表时,我得到了同样的错误。

你能指引我正确的方向吗? 提前致谢。

【问题讨论】:

  • 您实例化了数组titleItems,因此arrayItems 引用的空间已分配,但您尚未将引用设置为arrayItems 类的有效实例。
  • 一种快速的解决方法是将public class arrayItems 更改为public struct arrayItems,然后arrayItems 将成为值类型,而不是引用类型。但是,这可能会产生其他不良副作用。

标签: c# arrays list object reference


【解决方案1】:

您需要初始化数组中的每个列表:

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[i,j,k] = new arrayItems()吗?
  • 你的意思是:"Program.tileItems[x, y, z].items = new List();"
  • 我想我更喜欢 xyz 用于迭代器,但是是的。
  • @Theoden 不,您需要先创建arrayItems 本身的实例,它们不是神奇地创建的。此外,当使用行public List&lt;items&gt; items = new List&lt;items&gt;(); 创建每个arrayItems 对象时,您将创建列表的一个新实例。由于您有 new 关键字,因此您知道正在创建一个 new 列表。
  • @Jodrell i、j 和 k 是深度 3 时循环变量的标准变量名。
【解决方案2】:

由于您已经在类定义中初始化列表,因此无需在循环中重新初始化 arrayItems 的列表属性。

您有一个数组,其中包含一堆指向任何内容的指针。所以你实际上需要先在每个数组元素中创建一个新的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();
        }
    }
}

【讨论】:

    【解决方案3】:

    您正在创建arrayItems 的数组,这是一个引用类型,因为您将它定义为一个类。所以当你初始化你的数组时,默认情况下所有元素都会被分配null。这就是你得到错误的原因。您必须初始化数组的每个元素。

    【讨论】:

      猜你喜欢
      • 2012-10-30
      • 1970-01-01
      • 2019-10-26
      • 2023-02-21
      • 2014-05-23
      • 2012-10-08
      • 1970-01-01
      • 2010-10-24
      相关资源
      最近更新 更多