C# 如何从另一个案例输出存储在类/开关案例中的数据?
我正在为初学者C#类编写一个控制台程序,我完全被卡住了。 程序中的菜单应该使用一个C# 如何从另一个案例输出存储在类/开关案例中的数据?,c#,C#,我正在为初学者C#类编写一个控制台程序,我完全被卡住了。 程序中的菜单应该使用一个开关()来处理,您可以在案例1中输入数据,然后在案例3中请求将其写出。 数据是通过调用类playback或live中的构造函数来存储的,我的问题是如何通过选择case 3将存储的数据写出? 这是我的全部代码: class Live { public string name; public string instrument; public Live(string name, string
开关()
来处理,您可以在案例1
中输入数据,然后在案例3
中请求将其写出。
数据是通过调用类playback
或live
中的构造函数来存储的,我的问题是如何通过选择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
循环之外声明变量,以便您以后可以访问它们。目前它们的范围仅限于案例标签。我想您应该能够添加多个实时
和回放
s
在您之外的while循环中为它们添加一个列表:
List<Live> sounds = new List<Live>();
在案例3中,您可以循环播放声音并“播放”它们:
顺便说一下,您的案例0可能是
exit=true代码>而不是环境。退出(0)
您是否需要只跟踪创建的最后一个实况
或回放
或两者中的一个,或两者的倍数?这将修复它,非常感谢!在我发布之前,我曾试图在开关
之外声明它们,因为我认为这可能是问题所在,但我没有考虑while
循环。是的,你是对的,这很有效!当我的第一个问题解决时,我本来打算解决这个问题,但现在你为我节省了很多时间,所以非常感谢!
sounds.Add(live); // or sounds.Add(playback);
foreach(var sound in sounds)
{
Console.WriteLine(sound.ToString());
}