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

Can I use a variable in a switch statement?

我正在编写基于文本的冒险,遇到了问题。我正在尝试制作一个 switch 语句 case 来处理您想要的每个检查操作,并且到目前为止我的代码得到了这个:

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 语句中使用变量?我想要任何以 "examine" + (x) 开头的字符串来触发这种情况。

您的场景比 switch 语句更适合 if-else 语句。在 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