C# 在其范围之外打断循环
如果我有C# 在其范围之外打断循环,c#,C#,如果我有 string command = null; while(command != "exit") { Console.Write(">$"); ProcessCommand(Console.ReadLine()); } public static void ProcessCommand(string Command) { if(Command == "exit") break; }
string command = null;
while(command != "exit")
{
Console.Write(">$");
ProcessCommand(Console.ReadLine());
}
public static void ProcessCommand(string Command)
{
if(Command == "exit") break;
}
这不起作用,因为循环不在调用函数上,有没有办法在我从循环作用域调用的函数中中断循环
看看这有多难看
string command = null;
while(command != "exit")
{
Console.Write(">$");
command = Console.ReadLine();
if(command == "exit") break;
ProcessCommand(command);
}
而是从方法中返回bool
public static bool ProcessCommand(string Command)
{
if(command == "exit") return false;
}
while(command != "exit")
{
Console.Write(">$");
if(!ProcessCommand(Console.ReadLine())) break;
}
你为什么要分手?您已经在while循环中进行测试了吗?因此,只需分配command=Console.ReadLine(),然后当它==“exit”时,循环将自动退出。您必须在
while
中包含break
语句,而不是在其他方法中。你可以这样写:
bool continueLoop;
do
{
Console.Write(">$");
continueLoop = ProcessCommand(Console.ReadLine());
} while (!continueLoop);
public static bool ProcessCommand(string command)
{
return command != "exit";
}
这没用。
return
语句将从ProcessCommand
方法返回。@Joe,这就是我想要的,只要它返回循环中断,因为command=“exit”,我想知道为什么除了noob himself之外没有人想到这个答案对不起,我错过了参数前面的command=
。在这种情况下,ProcessCommand
在其当前的伪装下不做任何事情(可能这只是为了演示)。一种更具可读性的格式是在前面的行上分配命令,并将其作为参数传递给ProcessCommand
,前提是该方法确实做了一些事情。@Joe它做了很多事情;)我只是加入了退出部分,让它更简单。。。对我来说,这只是一种代码的味道,而你在原始问题中得到的更好,我建议你这样做,完全是你的选择。
string command = null;
while(command != "exit")
{
Console.Write(">$");
ProcessCommand(command=Console.ReadLine());
}
public static void ProcessCommand(string Command)
{
if(Command == "exit") return;
}