您可以使用一个布尔变量来将游戏结束通知给循环。该命令必须在循环中查询,并且由于在循环开始时不知道该命令,因此我会将循环条件放在循环结尾。
bool doExit = false;
do {
string command = Console.ReadLine().ToLower();
switch (command) {
case "exit":
case "quit":
doExit = true;
break;
case "otherCommand":
HandleOtherCommand();
break;
case "?":
case "h":
case "help":
PrintHelp();
break;
default:
Console.WriteLine("Invalid command!");
PrintHelp();
break;
}
} while (!doExit);
使用布尔变量的优点是,当满足其他条件时可以轻松终止游戏。例如当玩家赢得或失败时。
现在的方法。您可以将方法放置在相同的源代码(Program.cs)中或创建新的类。在计划内。CS你会写类似
private static void PrintHelp()
{
Console.WriteLine("Valid commands:");
Console.WriteLine("help, h, ?: Print this help.");
Console.WriteLine("exit, quit: End this game.");
Console.WriteLine("...");
}
注意,由于Main
方法是静态的,这同一个类中的其他方法必须是静态的了。如果您为命令创建其他类,则可以选择是否要创建静态类。静态类只是放置方法的地方。
static class GameCommands
{
// The `public` modifier makes it visible to other classes.
public static void PrintHelp()
{
...
}
public static void SomeOtherCommand()
{
...
}
}
您可以使用className.MethodName()
语法调用此类方法。
GameCommands.PrintHelp();
如果您必须存储不同的状态(例如分数)。创建非静态类是合适的。您可以创建类称为类实例或对象的类的副本。这实际上只复制类的状态,而不是方法代码。非静态方法可以作用于这种状态(字段,属性)。
class Player
{
// Constructor. Initializes an instance of the class (an object).
public Player (string name)
{
Name = name;
}
// Property
public int Score { get; private set; }
// Property
public string Name { get; private set; }
// Instance method (non-static method) having a parameter.
public void IncreaseScoreBy(int points)
{
Score += points;
}
public void PrintWinner()
{
Console.WriteLine("The winner is {0} with a score of {2} points." Name, Score);
}
}
可以使用这样一类这样的
Player player1 = new Player("John"); // Pass an argument to the constructor.
Player player2 = new Player("Sue");
player1.IncreaseScoreBy(5);
player2.IncreaseScoreBy(100);
if (player1.Score > player2.Score) {
player1.PrintWinner();
} else if (player2.Score > player1.Score)
player2.PrintWinner();
} else {
Console.WriteLine("The score is even!");
}
我们使用没有返回值的方法到现在为止。这通过替换返回类型的void关键字来表示。
void MethodWithNoReturnValue() { ... }
如果你有一个返回值(即你的方法是一个函数),你必须指定返回类型。 return
语句终止函数并指定返回值。
double Reciprocal(double x)
{
return 1.0/x;
}
你将同一类
double y = Reciprocal(x);
内或与对象名称或类名前面加上它,如果它是静态的称呼它。
什么问题? – Pete 2013-02-11 14:01:51
以后请格外小心。清理起来很麻烦! – PhonicUK 2013-02-11 14:04:23
我更新了帖子,使问题更加清晰。您向我们展示代码的事实告诉我们您尝试了什么,并允许我们为您提供帮助。在您展示您尝试过的内容并解释问题所在之处后,无需解释“您可以在哪里进行自己的研究”。一定要问更直接的问题以避免混淆。 – 2013-02-11 14:18:41