如何将值从struct放入数组?

时间:2015-04-16 18:56:19

标签: c# arrays

我试图像下面这样做,但是对于下一个操作,我想输出一个由3-5个结构组成的数组。 我想这样做:string[] my_array = {struct1,struct2,struct3};但不知道如何更正。

 public struct student
{
    public string Name { get; set; }
    public string Last_Name { get; set; }
    public DateTime Birthday { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public int Zip { 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.Birthday = new DateTime(1983, 12, 03);
        student_info.Address = "Baker str. 84/4a";
        student_info.City = "New LM";
        student_info.Zip = 90541;
        student_info.Country = "Paris";

       string[] my_array = { student_info.Name, student_info.Last_Name, student_info.Birthday.ToString(), student_info.Address, student_info.City, student_info.Zip.ToString(), student_info.Country };

       for (int counter = 0; counter < my_array.Length; counter++)
       {
           Console.WriteLine(my_array[counter]);
        }


    }
}

2 个答案:

答案 0 :(得分:2)

我不完全确定我明白你在做什么。但这是我最好的猜测。

如果对象都是相同的结构,你可以使用它。

student[] args = new [] { struct1, struct2, struct3 };

如果它们不是同一类型,那么这三个结构之间的最大公分母将是object。所以,

object[] args = new object[] { struct1, struct2, struct3 };

另一方面,如果您希望将三个结构组合成一个单独的字符串数组,就像您向我们展示的那样,这有点不同,我可以告诉您,如果你确认这实际上就是你要找的东西。

答案 1 :(得分:1)

您可以创建结构数组。

student[] my_array = new student[] {struct1,struct2,struct3};