创建由结构值组成的数组

时间:2015-04-17 11:43:29

标签: c# arrays

如何在不使用锯齿状数组的情况下创建正确的struct数组?我试过了 -

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

但我在控制台

中得到“project name.student”
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 个答案:

答案 0 :(得分:3)

你得到'project name.student'的原因是这是你的struct的ToString()方法的默认输出。 您需要向Student结构添加ToString()的覆盖,该结构将返回您想要写入控制台的任何内容。

另一个选项是向您的Console.WriteLine发送一个结构的属性,例如Console.WriteLine(newarray[0].Name);(由fix_likes_codingHellfire建议在此问题的其他答案中 )

你可以使用任何这些选项,根据我个人的喜好,ToString的覆盖看起来更优雅。

答案 1 :(得分:2)

您希望输出到控制台的是什么?

您看到的是由于默认object.ToString实现而导致的对象的完整类型名称。如果要查看某些内容,则需要选择要输出到控制台的属性,而不是对象。

改变这个:

 Console.WriteLine(newarray[0]);

对此:

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

,您的输出将是学生姓名。

答案 2 :(得分:2)

ProjectName.student是结构的类型。对象或结构的默认ToString()将打印其类型。 现在,根据您要写入输出的学生的属性,您可以执行以下操作:

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