为什么我会收到“对象引用错误"?用这个多维数组? [英] Why do I get an "object reference error" with this multi dimensional array?

查看:52
本文介绍了为什么我会收到“对象引用错误"?用这个多维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的班级同学

 public class pax
    {
        public pax();

        [SoapElement(DataType = "integer")]
        public string age { get; set; }
        public string firstName { get; set; }
        public string lastName { get; set; }
        public string paxType { get; set; }
        public string title { get; set; }
    }

并且我已经声明了以下数组

and i have declare the following array

pax[][]rooms=new pax[3][];

        rooms[0][0].paxType = "Adult";
        rooms[0][1].paxType="Adult";
        rooms[0][2].paxType="Child";
        rooms[0][2].age = "6";

它抛出错误对象引用未设置为对象的实例.在线

Its throwing an error Object reference not set to an instance of an object. on line

 rooms[0][0].paxType = "Adult";

推荐答案

这只会给你数组.

pax[][]rooms=new pax[3][];

要实例化对象,你必须new它:

To instantiate object, you have to new it:

rooms[0][0] = new pax();

您可能来自 C++ 并且可能认为对象数组会自动创建所有对象,但这里的情况并非如此 - 在您创建之前,您必须创建每个对象,因为它是 null.

You might be coming from C++ and may think that object array automatically create all objects, but that's not the case here - you will have to create each one because it is null before you do it.

因为这里有锯齿状数组:

Since you have jagged array here:

pax[][]rooms=new pax[3][];
rooms[0]=new pax[3];
rooms[0][0]=new pax();

锯齿状数组 = 数组数组.如果你需要多维(二维数组),那就是另一回事了,你会说:

Jagged array = array of arrays. If you need multidimensional (2-dimensional array), that's different story, and you would say:

pax[,] rooms=new pax[3,3];

例如...

这篇关于为什么我会收到“对象引用错误"?用这个多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆