在对象数组中填充数据变量

时间:2013-10-06 18:44:33

标签: c# c#-3.0 nullreferenceexception

class Customer
{
 public string name;
 public sting nic;
 public int age;

 public void add_customer()
    {
        // some code here to assign the values to the data types
    }
}

class main_menu
{
   Customer[] cust = new Customer[100];
   // some other data members

   public void new_customer()
   {
      // Some Console.WriteLine pritings
      cust[0].add_customer();
      // ------>> Now here in this line error is arrising which says
      An unhandled exception of type 'System.NullReferenceException' occurred in   Assignment 2.exe

      Additional information: Object reference not set to an instance of an object.


   }
}

现在我想做的是在所有客户实例中逐个填充对象数组中的数据变量

请帮助我,因为我是初学者

2 个答案:

答案 0 :(得分:0)

cust[0]为null,因此在为其赋值之前尝试访问其中一个属性或方法将导致此异常。

你主要的误解 - 通过初始化cust你没有初始化其中的任何一个对象(cust [i]对于每个我都是null)。

您需要在使用之前对其进行验证:

class main_menu
{
   Customer[] cust = new Customer[100];
   // some other data members

   public void new_customer()
   {
    cust[0] = new Customer();

      // when you want to use it later on, do this validation.
    if (cust[0] != null)
    {      
        cust[0].add_customer();
    }
   }
}

答案 1 :(得分:0)

在您的代码中,您生成一个集合来容纳100个客户对象,然后您尝试填充第一个客户的字段,但在集合中它尚不存在。在C#中,我们生成一个空集合,然后使用完全初始化的Customer对象填充此集合。类似的东西:

public class main_menu
{
  List<Customer> customers = new List<Customer>(); // empty collection of Customer's
  public void new_customer(string name, string nickname, int age)
  {
    customers.Add( new Customer { name, nickname, age } );
  }
} 

您应该看到两条新闻,一条用于集合,另一条用于插入集合中的每个(引用)对象。