我如何在对象数组中存储数据并在C#中一次显示/读取所有数据

时间:2018-10-17 14:20:38

标签: c# arrays .net

我正在制作一个项目,当我使用对象数组从用户那里获取数据时遇到了问题。 当我运行程序时,它要求输入数据的次数不限。但是它仅打印用户第一次输入的数据。 不,我不能使用列表,只能使用数组。这是问题的要求

using System;
namespace agentX
{
 class Application
  {
    private static int x;
    static void Main(string[] args)
    {
        Console.WriteLine("Enter the number of passengers");
        x=int.Parse(Console.ReadLine());
        Customer[] S = new Customer[x];

        for (int i = 0; i < x; i++)
        {
            S[i] = new Customer();
            S[i].SetInfo();
        }
        for (int j = 0; j < x; j++)
        {
            S[j].printInfo();
        }

    }
 }
 class Customer
{
    //private data members
    private int rollno;
    private string name;
    private int age;

    //method to set student details
    public void SetInfo()
    {
        Console.WriteLine("Enter the name ");
        this.name=Console.ReadLine();
        Console.WriteLine("Enter the roll number");
        this.rollno = int.Parse(Console.ReadLine());
        Console.WriteLine("Enter the age");
        this.age = int.Parse(Console.ReadLine());
    }

    public void printInfo()
    {
        Console.WriteLine("\r\nStudent Record: ");
        Console.WriteLine("\tName     : " + this.name);
        Console.WriteLine("\tRollNo   : " + this.rollno);
        Console.WriteLine("\tAge      : " + this.age);
        Console.ReadKey();
    }
}

}

This is the output

1 个答案:

答案 0 :(得分:2)

要从printInfo方法中将最后一行Console.ReadKey();移到最后一个循环下的Main。原因是Console.ReadKey()会阻塞循环,直到您按下某个键为止。

public void printInfo()
{
    Console.WriteLine("\r\nStudent Record: ");
    Console.WriteLine("\tName     : " + this.name);
    Console.WriteLine("\tRollNo   : " + this.rollno);
    Console.WriteLine("\tAge      : " + this.age);

}

static void Main(string[] args)
{
    Console.WriteLine("Enter the number of passengers");
    x=int.Parse(Console.ReadLine());
    Customer[] S = new Customer[x];

    for (int i = 0; i < x; i++)
    {
        S[i] = new Customer();
        S[i].SetInfo();
    }
    for (int j = 0; j < x; j++)
    {
        S[j].printInfo();
    }

    Console.ReadKey();
}