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

5

我正在编写一个基于文本的冒险游戏,遇到了一个问题。我想要创建一个 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) 开头的任何字符串都触发 case。


1
你的意思是将其作为一个变量 Console.WriteLine("That isn't an object to examine"); 吗? - julianstark999
2
switch语句中的case必须是常量,不能包含变量。 - M.kazem Akhgary
我修改了你的问题以使其更清晰,如果我理解正确,请告诉我 :) - Nate Barbettini
1个回答

5
您的情况最适合使用if-else语句,而不是switch语句。在C#中,switch只能对值进行评估,而不能对表达式进行评估。这意味着您无法执行以下操作:
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

1
应该将 case StartsWith( 改为 case input.StartsWith( 吗?否则非常好的答案。 - user585968
1
@MickyD 谢谢你的发现! - Nate Barbettini
1
如果你想获取你的 x 变量,你可以在 if 语句内部执行 string x = s.Split(new[] { "examine" }, StringSplitOptions.RemoveEmptyEntries)[0] - Arthur Rey
@ArthurRey,它说字符串不包含“examine”的定义,有什么想法吗? - Fireball175
@Fireball175 如果 x 是一个字符串,那么 x.examine() 将会失败。 - Arthur Rey
1
@ArthurRey 正在努力解决问题,但非常感谢您的帮助,我真的很感激。 - Fireball175

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接