【问题标题】:How can i store data in an array of object and display/read all of them at once in c#如何将数据存储在对象数组中并在 C# 中一次显示/读取所有数据
【发布时间】:2018-10-17 14:20:38
【问题描述】:

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

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();
    }
}

}

【问题讨论】:

  • 您在printInfo() 方法的末尾有Console.ReadKey();,因此您需要在每个对象打印完其信息后按一个键才能继续循环。
  • 我现在感觉太笨了,发布这个问题后几秒钟我按下了一个按钮......我很抱歉浪费大家的时间
  • @TarunBisht 发生这种错误。
  • 发生在我们最好的人身上:)

标签: c# arrays .net


【解决方案1】:

从您的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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 2021-03-26
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多