如何从另一个事例输出存储在类/开关事例中的数据

本文关键字:开关 数据 存储 另一个 输出 | 更新日期: 2023-09-27 18:27:15

我正在为一个初学者C#类编写控制台程序,我完全被卡住了。程序中的菜单应该用switch()处理,在case 1中输入数据,然后可以请求在case 3中写出数据。数据是通过调用类playbacklive中的构造函数来存储的,我的问题是如何通过选择case 3来写出存储的数据?这是我的全部代码:

class Live
{
    public string name;
    public string instrument;
    public Live(string name, string instrument)
    {
        this.name = name;
        this.instrument = instrument;
    }
    public override string ToString()
    {
        return (string.Format("{0}{1}", name, instrument));
    }
    //default constructor for the constructor in Playback to work
    public Live()
    { }
}
class Playback : Live
{
    public int duration;
    public Playback(int duration)
    {
        this.duration = duration;
    }
    public override string ToString()
    {
        return (string.Format("{0}{1}", base.ToString(), duration));
    }
}
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("###### Menu: ######");
        Console.WriteLine("1. Add a Live");
        Console.WriteLine("2. Add a Playback");
        Console.WriteLine("3. Write out all objects");
        Console.WriteLine("0. End");
        Console.WriteLine("#################");
        bool exit = false;
        while (!exit)
        {
            int val = int.Parse(Console.ReadLine());
            switch (val)
            {
                case 1:
                    Console.WriteLine("Input name: ");
                    string namn = Console.ReadLine();
                    Console.WriteLine("Input instrument: ");
                    string instru = Console.ReadLine();
                    Live live = new Live(namn, instru);
                    break;
                case 2:
                    Console.WriteLine("Input duration: ");
                    string time = Console.ReadLine();
                    int tid = int.Parse(time);
                    Playback playback = new Playback(tid);
                    break;
                case 3:
                    Console.WriteLine(); //this is where I need to output the results
                    break;
                case 0:
                    Environment.Exit(0);
                    break;
            }
        }
    }
}

如何从另一个事例输出存储在类/开关事例中的数据

while循环之外声明变量,以便以后可以访问它们。目前,它们的范围仅限于大小写标签。

我想您应该能够添加多个LivePlayback

循环时为他们添加一个列表:

List<Live> sounds = new List<Live>();

由于Playback继承自Live,因此可以将回放添加到此列表中。

在情况1和情况2中,在定义了Live或Playback对象后,将其添加到列表中:

sounds.Add(live); // or sounds.Add(playback);

在你的情况3中,你可以循环播放这些声音:

foreach(var sound in sounds)
{
   Console.WriteLine(sound.ToString());
}

顺便说一下,你的情况0可能是exit=true;而不是Environment.Exit(0);