0

为什么在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
}
4

2 回答 2

2

你需要初始化你的数组:

schema.name = "schemaName";
schema.tables = new Tables[10];
schema.tables[0].name = "tables1";
于 2012-11-15T22:53:10.167 回答
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
}
于 2012-11-15T22:54:11.297 回答