【问题标题】:initializing 2Darray of Objects初始化二维对象数组
【发布时间】:2021-02-22 02:39:23
【问题描述】:

大家好,这段代码中发生了这个奇怪的事情

public CoreManager[][] mng = new CoreManager[5][];


void Start()
{
    for (int x = 0; x < 3; x++)
    {
        for (int y = 0; y < 3; y++)
        {
            mng[y] = new CoreManager[5];
            mng[x][y] = new CoreManager();
            mng[x][y].actual_words = new string[5];   
            mng[x][y].actual_words[y] = "test "+y;
            Debug.Log(mng[x][y].actual_words[y]); //this code work fine and show the elements in the log
        }
    }
    Debug.Log(mng[0][0].actual_words[0]);//this code gives an error 
}

这是来自统一引擎的调试日志:

如您所见,如果我尝试打印它会给我一个错误 初始化后数组的值,尽管如果它在初始化时位于 for 循环内,它会毫无问题地打印它

我昨天在这上面花了 7 个小时 :D

【问题讨论】:

  • 我强烈推荐关注this Microsoft debugger tutorial
  • 不清楚您对这段代码的期望是什么,因为您似乎使用xy 来表示许多不同的东西。奇怪的是,您声明 mng 包含 5 个数组,然后您只使用了 3 个插槽。然后,您使用y 来表示嵌套数组中的位置和actual_words 数组中的位置。

标签: c# arrays unity3d object


【解决方案1】:

你有点把自己打成结了。第一个问题是您混淆了mng 项目上的索引器,即mng[x],然后您使用mng[y]。您还在第二个循环中重新声明了不需要的项目。

试试这个代码并将其用作您的模板。它应该可以解决问题:

void Start ( )
{
    for (int x = 0; x < 3; x++)
    {
        mng[x] = new CoreManager[5];
        for (int y = 0; y < 3; y++)
        {
            var c = new CoreManager();
            c.actual_words = new string[5];
            for (var z = 0; z < c.actual_words.Length; z++)
                c.actual_words[z] = $"Manager [{x}][{y}] Actual Word [{z}]";

            mng[x][y] = c;
        }
    }
    Debug.Log (mng[0][0].actual_words[0]);//this code gives an error 
}

【讨论】:

    【解决方案2】:

    您的代码有多个问题:

    首先,mng 使用 5 个元素的计数进行初始化,for 循环只迭代 3 个元素。

    然后,在mng 中设置某些内容的第一条指令在第二个循环中,使用y 迭代器,所有后续指令都使用x 迭代器代替它。

    以下是可能的解决方案:

    public const int Length0 = 5;
    public const int Length1 = 5;
    public CoreManager[][] mng = new CoreManager[Length0][];
    
    void Start()
    {
        for (int x = 0; x < Length0; x++)
        {
            var mng_x = new CoreManager[Length1];
            mng[x] = mng_x;
    
            for (int y = 0; y < Length1; y++)
            {
                var mng_x_y = new CoreManager();
                mng_x[y] = mng_x_y;
    
                mng_x_y.actual_words = new string[5];   
                mng_x_y.actual_words[y] = "test " + y;
                Debug.Log(mng_x_y.actual_words[y]); //this code work fine and show the elements in the log
            }
        }
        Debug.Log(mng[0][0].actual_words[0]);//this code gives an error 
    }
    

    请注意,局部变量 mng_xmng_x_y 有助于避免在声明后的整个指令中使用错误的索引;此外,它们避免了多次获取相同的数组元素。

    【讨论】:

      猜你喜欢
      • 2017-07-23
      • 2014-02-18
      • 1970-01-01
      • 1970-01-01
      • 2012-11-29
      相关资源
      最近更新 更多