以前一直没有在C#中创建过对象数组,今天写了个小练习,结果用到对象数组的时候不会用了。
在C#中创建对象数组不像C++。
代码:
Student[] student=new Student[5];
这里在创建对象数组的时候没有用括号指定参数,不像创建单个对象那样
创建单个对象的代码:
Student student=new Student();
同时如果在创建对象数组的时候前面的数组维数中括号不能指定维数,如果指定维数则编译出错:
Student[5] student=new Student[5]; //这里是编译不过去的。
请注意, 在创建一个对象数组以后,没有生成任何对象,而是简单一个对对象的引用的数组,如果这个时候要使用对象,会出现空指针引用。在具体的使用数组中每一个引用的时候,还需要用new 创建对象.
Student[] student = new Student[5];
student[0] = new Student();
student[0].Age = 12;
student[1] = new Student();
student[1].Age = 13;
student[2] = new Student();
student[2].Age = 74;
student[3] = new Student();
student[3].Age = 34;
student[4] = new Student();
student[4].Age = 32;
然后才可以使用对象数组。这里和C++是不一样的。也就是说,每一个数组元素都要单独的初始化。