【问题标题】:How to use array member?如何使用数组成员?
【发布时间】:2012-11-15 22:51:35
【问题描述】:

为什么在struct中使用struct array会报错?

public struct Tables
{
    public string name;
}

public struct Schema
{
    public string name;
    public Tables[] tables; //Declarate struct array in struct
}

我在这段代码中使用了 struct:

Schema schema;

private void Form1_Load(object sender, EventArgs e)
{
    schema.name = "schemaName";
    schema.tables[0].name = "tables1Name"; // Error in here: Object reference not set to an instance of an object
}

【问题讨论】:

  • 我已经从标题中删除了对结构的提及...如果不同意,请随时恢复编辑。

标签: c# arrays struct


【解决方案1】:

你需要初始化你的数组:

schema.name = "schemaName";
schema.tables = new Tables[10];
schema.tables[0].name = "tables1";

【讨论】:

    【解决方案2】:

    这是因为schema.tables 从未初始化,因此为空

    试试

    private void Form1_Load(object sender, EventArgs e)
    {
        schema.name = "schemaName";
        schema.tables = new Tables[5];
        schema.tables[0].name = "tables1"; // Error ini here: Object reference not set to an instance of an object
    }
    

    【讨论】:

      猜你喜欢
      • 2011-07-29
      • 1970-01-01
      • 2019-07-02
      • 1970-01-01
      • 1970-01-01
      • 2014-10-24
      • 1970-01-01
      • 2020-05-06
      • 2018-12-31
      相关资源
      最近更新 更多