以前一直沒有在C#中建立過對象數組,今天寫了個小練習,結果用到對象數組的時候不會用了。
在C#中建立對象數組不像C++。
代碼:
view plaincopy to clipboardprint?
- Student[] student=new Student[5];
Student[] student=new Student[5];
這裡在建立對象數組的時候沒有用括弧指定參數,不像建立單個對象那樣
建立單個對象的代碼:
view plaincopy to clipboardprint?
- Student student=new Student();
Student student=new Student();
同時如果在建立對象數組的時候前面的數組維數中括弧不能指定維數,如果指定維數則編譯出錯:
Student[5] student=new Student[5]; //這裡是編譯不過去的。
請注意, 在建立一個對象數組以後,沒有產生任何對象,而是簡單一個對對象的引用的數組,如果這個時候要使用對象,會出現null 指標引用。在具體的使用數組中每一個引用的時候,還需要用new 建立對象.
view plaincopy to clipboardprint?
- 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#中建立過對象數組,今天寫了個小練習,結果用到對象數組的時候不會用了。
在C#中建立對象數組不像C++。
代碼:
view plaincopy to clipboardprint?
- Student[] student=new Student[5];
Student[] student=new Student[5];
這裡在建立對象數組的時候沒有用括弧指定參數,不像建立單個對象那樣
建立單個對象的代碼:
view plaincopy to clipboardprint?
- Student student=new Student();
Student student=new Student();
同時如果在建立對象數組的時候前面的數組維數中括弧不能指定維數,如果指定維數則編譯出錯:
Student[5] student=new Student[5]; //這裡是編譯不過去的。
請注意, 在建立一個對象數組以後,沒有產生任何對象,而是簡單一個對對象的引用的數組,如果這個時候要使用對象,會出現null 指標引用。在具體的使用數組中每一個引用的時候,還需要用new 建立對象.
view plaincopy to clipboardprint?
- 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;