2015-04-17 118 views
0

如何在不使用鋸齒陣列的情況下創建正確的結構數組?我曾嘗試 -創建包含結構值的數組

student[] newarray = new student[]{student_info,student2_info}; 
Console.WriteLine(newarray[0]); 

但我在控制檯

public struct student 
{ 
    public string Name { get; set; } 
    public string Last_Name { get; set; } 
    public string Address { get; set; } 
    public string City { get; set; } 
    public string Country { get; set; } 
} 
class H 
{ 
    static void Main(string[] args) 
    { 
     student student_info = new student(); 
     student_info.Name = "Mike"; 
     student_info.Last_Name = "Johnson"; 
     student_info.Address = "Baker str. 84/4a"; 
     student_info.City = "New LM"; 
     student_info.Country = "Paris"; 

     student student2_info = new student(); 
     student student3_info = new student(); 
     student student4_info = new student(); 
     student student5_info = new student(); 

     string[] my_array1 = { student_info.Name, student_info.Last_Name, student_info.Address, student_info.City, student_info.Country }; 
     string[] my_array2 = { student2_info.Name, student2_info.Last_Name, student2_info.Address, student2_info.City, student2_info.Country }; 
     string[] my_array3 = { student3_info.Name, student3_info.Last_Name, student3_info.Address, student3_info.City, student3_info.Country }; 
     string[] my_array4 = { student4_info.Name, student4_info.Last_Name, student4_info.Address, student4_info.City, student4_info.Country }; 
     string[] my_array5 = { student5_info.Name, student5_info.Last_Name, student5_info.Address, student5_info.City, student5_info.Country }; 

     string[][] list = new string[][] { my_array1, my_array2, my_array3, my_array4, my_array5 }; 
     for (int x = 0; x < 5; x++) 
     { 
      for (int y = 0; y <= 4; y++) 
      { 
       // Console.WriteLine(list[x][y]); 
      } 

      student[] newarray = new student[]{student_info,student2_info}; 
      Console.WriteLine(newarray[0]); 
     } 
    } 
} 

回答

3

你得到'project name.student'的原因是這是你的struct的ToString()方法的默認輸出。 您需要將ToString()重寫添加到您的Student結構中,該結構將返回想要寫入控制檯的任何內容。

另一種選擇是發送到Console.WriteLine命令你的結構的屬性,如Console.WriteLine(newarray[0].Name);(如建議在其他的答案fix_likes_codingHellfire這個問題 )

您可以使用其中任一選項,根據我個人的喜好,ToString的覆蓋看起來更加優雅。

+0

優雅取決於意圖是什麼,如果你只是想輸出的名字,那麼首先是更優雅,如果你想輸出「Name LastName(Address)」覆蓋ToString比串聯或string.format好得多) – rbuddicom

+0

@Hellfire:是的,不是。它通常更優雅,因爲您不必在Console.WriteLine中指定屬性。它封裝在'ToString()'中。但是,如果常見用途是顯示全名,而在另一種情況下,您希望僅顯示第一個名稱,當然優雅的方法是使用'ToString()'返回全名並寫入'Console.WriteLine( newarray [0]請將.Name);' –

2

得到「項目name.student」你希望輸出到控制檯?

由於默認的object.ToString實現,您所看到的是對象的完整類型名稱。你需要選擇屬性輸出到控制檯,而不是對象,如果你想看到的東西。

更改此:

Console.WriteLine(newarray[0]); 

要這樣:

Console.WriteLine(newarray[0].Name); 

,你的輸出將是學生的名字。

2

ProjectName.student是結構的類型。對象或結構的默認ToString()將打印其類型。 現在取決於你想要寫輸出,你可以像做學生的哪些屬性:

Console.WriteLine(String.Format("Students name: {0}", newarray[0].Name));