我只是想知道在c#中是否有办法使用另一个案例激活案例。 E.g
{
switch
case "Music":
//play music string
{
case "Song Name":
messagebox.show("Playing Song Name");
break;
case "Song 2":
messagebox.show("Playing Song 2");
break;
}
}
有没有人对我如何做到这一点有任何想法?我也在使用语音识别引擎和合成器。
答案 0 :(得分:2)
可以做到,但可能有更好的方法来实现你的目标。为了做到这一点,你需要传入一个具有多个属性的结构或对象,这样一旦第一个开关碰到正确的情况,就可以提取打开的值。
TL; DR嵌套切换案例是可能的,但不明智。
答案 1 :(得分:1)
我不明白为什么不:
switch (action)
{
case "Music":
switch(songName
{
case "Song Name":
messagebox.show("Playing Song Name");
break;
case "Song 2":
messagebox.show("Playing Song 2");
break;
}
case "Video":
break;
}
但是,似乎这可能更容易维护和更容易阅读:
public MyActionMethod(MyAction action)
{
switch (action)
{
case Music:
MessageSong(songName);
break;
case Video:
break;
}
}
public void MessageSong(string songName)
{
switch(songName)
{
case "Song Name":
messagebox.show("Playing Song Name");
break;
case "Song 2":
messagebox.show("Playing Song 2");
break;
}
}
public enum MyAction
{
NoAction,
Music,
Video
}
答案 2 :(得分:0)
您的语法不正确,但是,据我所知,您希望在另一个switch语句中进行切换?那是可行的:
string type = "Music";
string songName = "song1";
switch(type)
{
case "Music":
{
switch(songName)
{
case "song1":
//play song1
break;
case "song2":
//play song2
break;
}
}break;
case "SomeOtherType":
break;
}
答案 3 :(得分:-1)
你想要这样的东西吗?
string on1 = "Music";
string on2 = "Song Name";
switch (on1) {
case "Music":
switch (on2)
{
case "Song Name":
System.Windows.Forms.MessageBox.Show("Playing Song Name");
break;
case "Song 2":
System.Windows.Forms.MessageBox.Show("Playing Song 2");
break;
}
break;
}
答案 4 :(得分:-1)
不确定你的意思,但这是我的看法:
string type = "";
string song = "";
switch (type)
{
case "Music":
switch (song)
{
case "Song Name":
messagebox.show("Playing Song Name");
break;
case "Song 2":
messagebox.show("Playing Song 2");
break;
}
break;
default:
// whatever
break;
}
编辑:由于您在第二个开关中执行相同的操作,您可以执行以下操作:
string type = "";
string song = "";
switch (type)
{
case "Music":
messagebox.show("Playing " + song);
break;
default:
// whatever
break;
}