C# 中创建对象数组

以前一直没有在C#中创建过对象数组,今天写了个小练习,结果用到对象数组的时候不会用了。

 

在C#中创建对象数组不像C++。

 

代码:

 

  1. Student[] student=new Student[5];  


 

这里在创建对象数组的时候没有用括号指定参数,不像创建单个对象那样

创建单个对象的代码:

  1. Student student=new Student();  


同时如果在创建对象数组的时候前面的数组维数中括号不能指定维数,如果指定维数则编译出错:

Student[5] student=new Student[5]; //这里是编译不过去的。

 

请注意, 在创建一个对象数组以后,没有生成任何对象,而是简单一个对对象的引用的数组,如果这个时候要使用对象,会出现空指针引用。在具体的使用数组中每一个引用的时候,还需要用new 创建对象.

  1. Student[] student = new Student[5];  
  2.            student[0] = new Student();  
  3.            student[0].Age = 12;  
  4.            student[1] = new Student();  
  5.            student[1].Age = 13;  
  6.            student[2] = new Student();  
  7.            student[2].Age = 74;  
  8.            student[3] = new Student();  
  9.            student[3].Age = 34;  
  10.            student[4] = new Student();  
  11.            student[4].Age = 32;  
posted @ 2011-09-28 11:12  星月磊子  阅读(5081)  评论(2编辑  收藏  举报