RayWu2019
RayWu2019
2019-10-18 13:55
采纳率: 100%
浏览 873

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • qq_39815900
    沫琉璃 2019-10-18 14:28
    已采纳

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

    点赞 评论
  • caozhy
    struct CAOZUO_STRUCT
    {
        public Single WenDu;
        public string[] XiangMu = new string[2];
        public Single[] ShuZhi = new Signle[2];
    }
    
    点赞 评论
  • qq_35378370
    OnePiece白胡子 2019-10-18 16:06

    new一个对象即可!

    点赞 评论

相关推荐