【问题标题】:Null Reference Exception when calling an Object Array [duplicate]调用对象数组时出现空引用异常[重复]
【发布时间】:2013-02-12 17:15:46
【问题描述】:

我之前曾尝试寻求帮助,但我认为我提供的信息不足,但我很感谢所有的建议。

目标只是将 Object Room 的新实例添加到数组并打印到列表框。当用户尝试输入已经存在的房间名称时,它应该简单地显示在数组中已经存在的房间的规范中。

我不断收到空引用异常。

这是我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace Room_Class
{
    public partial class Form1 : Form
    {
        Room[] roomArray = new Room[20];
        int count = 0;

        public Form1()
        {
            InitializeComponent();
        }

        private void btnAddRm_Click(object sender, EventArgs e)
        {
            double length, width, height;
            if (VerifyRoomName() == true)
            {


                if (txtRmLen.Text == "" || txtRmWid.Text == "" || txtRmHt.Text == "")
                {
                    for (int i = 0; i < roomArray.Length; i++)
                    {
                        if (txtRmName.Text == roomArray[i].getRoomName())
                        {
                            txtRmName.Text = roomArray[i].getRoomName();
                            txtRmLen.Text = roomArray[i].getLength().ToString();
                            txtRmHt.Text = roomArray[i].getCeilingHeight().ToString();
                            txtRmWid.Text = roomArray[i].getWidth().ToString();
                        }
                        else
                        {
                            roomArray[count] = new Room(roomName);
                            count++;
                        }
                    }
                }
                else
                {
                    try
                    {
                        length = double.Parse(txtRmLen.Text);
                        width = double.Parse(txtRmWid.Text);
                        height = double.Parse(txtRmHt.Text);
                        for (int i = 0; i < roomArray.Length; i++)
                        {
                            if (txtRmName.Text == roomArray[i].getRoomName())
                            {
                                txtRmName.Text = roomArray[i].getRoomName();
                                txtRmLen.Text = roomArray[i].getLength().ToString();
                                txtRmHt.Text = roomArray[i].getCeilingHeight().ToString();
                                txtRmWid.Text = roomArray[i].getWidth().ToString();
                            }
                            else
                            {
                                roomArray[count] = new Room(roomName, length, width, height);
                                count++;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message + "\n\nPlease Enter Valid Values", "Error!");
                    }
                }  
                PrintList();
            }

        }


        private void PrintList()
        {
            double paintTotal = 0, feetTotal = 0;
            string RoomName;
            lstRoomList.Items.Clear();
            for (int i = 0; i < count; i++)
            {
                RoomName = roomArray[i].getRoomName() + "\t" + roomArray[i].SquareFeet().ToString("n1") + "\t" + roomArray[i].GallonsPaint().ToString("n1");
                lstRoomList.Items.Add(RoomName);
                paintTotal += roomArray[i].GallonsPaint();
                feetTotal += roomArray[i].SquareFeet();
                lblTtlGallons.Text = paintTotal.ToString("n1");
                lblTtlSqFt.Text = feetTotal.ToString("n1");
            }
        }

        private bool VerifyRoomName()
        {
            if (roomName == "")
            {
                MessageBox.Show("Please Enter a Room Name", "Error!");
                return false;
            }
            else
                return true;
        }
    }
}

【问题讨论】:

标签: c# nullreferenceexception


【解决方案1】:

你的代码应该是

if (roomArray[i] != null)

每当您创建一个数组时,您必须先初始化它的各个项目,然后才能访问它们。

Room[] roomArray = new Room[20];

roomArray[0] = new Room();

【讨论】:

  • 正要给出相同的答案,但后来发现 OP 在这部分 roomArray[count] = new Room(roomName); 之类的部分中初始化 roomArray // 尽管将它放在其他部分是可疑的
  • @Bingo 是的,我也看到了......我只是想他最大的问题可能是理解如何使用数组,因此我的回答:)
【解决方案2】:

因为 Room[] 中的 Room 元素我们没有被初始化。

试试

public Form1()
{
    InitializeComponent();
    for(int i = 0; i < roomyArray.Length; i++) roomArray[i] = new Room();
}

【讨论】:

    【解决方案3】:

    正如其他答案所说,您需要在开始使用之前初始化数组。当你写:

    Room[] roomArray = new Room[20];
    

    您告诉计算机要做的是为您保留足够的内存来引用Room 类型的20 个对象。提出的其他解决方案很好,但如果您想要性能,请尝试以下方法:

    根据this SO 的回答,使用以下功能将比迄今为止提供的其他解决方案性能更高。这也有来自this blog post.的支持证据

    注意:我已转换为使用泛型

        /// <summary>
        /// Fills an array with a default value
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="array">The array to fill with a default value</param>
        /// <param name="value">The default value</param>
        public static void MemSet<T>(T[] array, T value)
        {
            if (array == null)
            {
                throw new ArgumentNullException("array");
            }
    
            int block = 32, index = 0;
            int length = Math.Min(block, array.Length);
    
            //Fill the initial array
            while (index < length)
            {
                array[index++] = value;
            }
    
            length = array.Length;
            while (index < length)
            {
                Buffer.BlockCopy(array, 0, array, index, Math.Min(block, length - index));
                index += block;
                block *= 2;
            }
        }
    

    用法

    Memset<Room>(roomArray, new Room());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-17
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多