C# 中建立對象數組

來源:互聯網
上載者:User

以前一直沒有在C#中建立過對象數組,今天寫了個小練習,結果用到對象數組的時候不會用了。

 

在C#中建立對象數組不像C++。

 

代碼:

 

view plaincopy to clipboardprint?
  1. Student[] student=new Student[5];  

Student[] student=new Student[5];

 

這裡在建立對象數組的時候沒有用括弧指定參數,不像建立單個對象那樣

建立單個對象的代碼:

view plaincopy to clipboardprint?
  1. Student student=new Student();  

Student student=new Student();

同時如果在建立對象數組的時候前面的數組維數中括弧不能指定維數,如果指定維數則編譯出錯:

Student[5] student=new Student[5]; //這裡是編譯不過去的。

 

請注意, 在建立一個對象數組以後,沒有產生任何對象,而是簡單一個對對象的引用的數組,如果這個時候要使用對象,會出現null 指標引用。在具體的使用數組中每一個引用的時候,還需要用new 建立對象.

view plaincopy to clipboardprint?
  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;  

以前一直沒有在C#中建立過對象數組,今天寫了個小練習,結果用到對象數組的時候不會用了。

 

在C#中建立對象數組不像C++。

 

代碼:

 

view plaincopy to clipboardprint?
  1. Student[] student=new Student[5];  

Student[] student=new Student[5];

 

這裡在建立對象數組的時候沒有用括弧指定參數,不像建立單個對象那樣

建立單個對象的代碼:

view plaincopy to clipboardprint?
  1. Student student=new Student();  

Student student=new Student();

同時如果在建立對象數組的時候前面的數組維數中括弧不能指定維數,如果指定維數則編譯出錯:

Student[5] student=new Student[5]; //這裡是編譯不過去的。

 

請注意, 在建立一個對象數組以後,沒有產生任何對象,而是簡單一個對對象的引用的數組,如果這個時候要使用對象,會出現null 指標引用。在具體的使用數組中每一個引用的時候,還需要用new 建立對象.

view plaincopy to clipboardprint?
  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;  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.