我可以在switch语句中使用变量吗?

时间:2016-07-08 05:15:59

标签: c# .net switch-statement console-application

我正在编写基于文本的冒险,并且遇到了问题。我正在尝试制作一个switch语句案例来处理你想要的每一个考试行动,到目前为止我的代码都是这样:

case "examine" + string x:
    //this is a method that I made that makes sure that it is an object in the area
    bool iseobj = tut.Check(x);
    if (iseobj)
        x.examine();
    else
        Console.WriteLine("That isn't an object to examine");
    break;

如何在case语句中使用变量?我希望任何以&#34开头的字符串;检查" +(x)触发案件。

1 个答案:

答案 0 :(得分:5)

您的方案比if-else语句更适合switch语句。在C#中,switch可以only evaluate values,而不是表达式。这意味着您不能执行:

case input.StartsWith("examine"):

但是,您可以使用if声明来完成此工作!请考虑执行以下操作:

if (input.StartsWith("examine"))
{
    //this is a method that I made that makes sure that it is an object in the area
    bool iseobj = tut.Check(x);
    if (iseobj)
        x.examine();
    else
        Console.WriteLine("That isn't an object to examine");
}
else if (...) // other branches here