C# 结构体数组里的成员变量也是数组,如何进行定义和初始化?下面代码运行时提示“其他信息: 未将对象引用设置到对象的实例。”

C# 结构体数组里的成员变量也是数组,如何进行定义和初始化?下面代码运行时提示“其他信息: 未将对象引用设置到对象的实例。”

问题描述:

namespace StructArrayTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
CaoZuoStructInit();
}

    struct CAOZUO_STRUCT
    {
        public Single WenDu;
        public string[] XiangMu;
        public Single[] ShuZhi;
    }
    CAOZUO_STRUCT[] CaoZuo = new CAOZUO_STRUCT[2];
    private void CaoZuoStructInit()
    {
        CaoZuo[0].WenDu = 25.0F;
        CaoZuo[0].XiangMu[0] = "电压";
        CaoZuo[0].XiangMu[1] = "电流";
        CaoZuo[0].ShuZhi[0] = 50.0F;
        CaoZuo[0].ShuZhi[1] = 2.0F;

        CaoZuo[1].WenDu = 25.0F;
        CaoZuo[1].XiangMu[0] = "电压";
        CaoZuo[1].XiangMu[1] = "电流";
        CaoZuo[1].ShuZhi[0] = 50.0F;
        CaoZuo[1].ShuZhi[1] = 2.0F;

    }
    private void Form1_Load(object sender, EventArgs e)
    {
    }
}

}

以上内容运行时会报错,“其他信息: 未将对象引用设置到对象的实例。”还会提示警告 1 从未对字段“StructArrayTest.Form1.CAOZUO_STRUCT.XiangMu”赋值,字段将一直保持其默认值 null E:\VS_CSharp_Project\StructArrayTest\StructArrayTest\Form1.cs 24 29 StructArrayTest

CaoZuo[0].XiangMu=new string[2]
那就在方法中将这个实例化

struct CAOZUO_STRUCT
{
    public Single WenDu;
    public string[] XiangMu = new string[2];
    public Single[] ShuZhi = new Signle[2];
}

new一个对象即可!