【发布时间】:2016-07-22 23:49:31
【问题描述】:
我想像这样:
prompt> checkprice
price of foo is 42$
prompt>
运行多个命令。
【问题讨论】:
-
如果你不知道如何正确表达,想象一下我和其他人理解你的问题有多难......
我想像这样:
prompt> checkprice
price of foo is 42$
prompt>
运行多个命令。
【问题讨论】:
也许这个
//this is your price variable
static int price = 42;
//function to check it
static void CheckPrice()
{
Console.WriteLine("price of foo " + price + "$");
}
static void Main()
{
bool exit = false;
do
{
//write at begin ">"
Console.Write(">");
//wait for user input
string input = Console.ReadLine();
// if input is "checkprice"
if (input == "checkprice") CheckPrice();
if (input == "exit") exit = true;
} while (!exit);
}
【讨论】:
直到键入特定命令,例如“退出”:
static void Main(string[] args) {
var line = System.Console.ReadLine().Trim();
while(line!="exit") {
myOperationCommand(line);
line = System.Console.ReadLine().Trim(); // read input again
}
System.Console.WriteLine("End!\n");
}
// Do some operation...
static void myOperationCommand(string line) {
switch(line) {
case "checkprice":
System.Console.WriteLine("price of foo is 42$");
break;
default:
System.Console.WriteLine("Command not reconized: " + line);
break;
}
}
【讨论】:
类似:
while(true) {
Console.Write("prompt>");
var command = Console.ReadLine();
if (command == "command1") doSomething();
else if (command == "command2") doSomethingElse();
...
else if (command == "quit") break;
}
【讨论】:
else if?你可以只做while ((command = Console.ReadLine().ToLower()) != "quit") {(这意味着你必须在循环之前声明command)。 --- 另外,.ToLower() 用于不区分大小写的命令。
.ToLower() 仍然很好用,这样即使你输入QUIT 或qUiT 等,你的程序仍然会执行你的命令。