我正在编写基于文本的冒险,并且遇到了问题。我正在尝试制作一个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)触发案件。
答案 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