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

Fir*_*175 4 .net c# console-application switch-statement

我正在编写基于文本的冒险,并且遇到了问题.我正在尝试创建一个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;
Run Code Online (Sandbox Code Playgroud)

如何在case语句中使用变量?我想要任何以"examine"+(x)开头的字符串来触发这个案例.

Nat*_*ini 5

您的场景if-else比声明更适合switch声明.在C#中,switch可以只评估值,而不是表达式.这意味着你不能做的:

case input.StartsWith("examine"):
Run Code Online (Sandbox Code Playgroud)

但是,您可以使用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
Run Code Online (Sandbox Code Playgroud)