如何在不使用鋸齒陣列的情況下創建正確的結構數組?我曾嘗試 -創建包含結構值的數組
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]);
}
}
}
優雅取決於意圖是什麼,如果你只是想輸出的名字,那麼首先是更優雅,如果你想輸出「Name LastName(Address)」覆蓋ToString比串聯或string.format好得多) – rbuddicom
@Hellfire:是的,不是。它通常更優雅,因爲您不必在Console.WriteLine中指定屬性。它封裝在'ToString()'中。但是,如果常見用途是顯示全名,而在另一種情況下,您希望僅顯示第一個名稱,當然優雅的方法是使用'ToString()'返回全名並寫入'Console.WriteLine( newarray [0]請將.Name);' –