【发布时间】:2017-12-19 18:08:25
【问题描述】:
我是 C# 的初学者,正在创建一个小 MadLibs 控制台游戏以供练习。 一切正常,现在我正在努力让它变得更好,代码更简洁等。 刚刚从单个字符串切换到用户输入和故事输出的数组,但我认为必须有一种更有效的方法来完成这两者。
播放器类
namespace MadLib
{
static class Player
{
public static string Input (string part)
{
string name;
Console.WriteLine("Please enter a {0}: ", part);
name = Console.ReadLine();
return name;
}
}
}
故事代码块
static class Story
{
static public void Spooky()
{
string[] part = new string[10];
//ask player for words
part[0] = Player.Input("noun");
part[1] = Player.Input("adjective");
part[2] = Player.Input("adjective");
part[3] = Player.Input("adjective");
part[4] = Player.Input("occupation");
part[5] = Player.Input("occupation");
part[6] = Player.Input("occupation");
part[7] = Player.Input("adjective");
part[8] = Player.Input("noun");
part[9] = Player.Input("noun");
//output finished story
Console.WriteLine("They all agreed that it was a huge {0}, {1}, {2}, and {3}."
+" I have cross-examined these men, one of them a hard-headed "
+ "{4}, one a {5}, and one a moorland {6}"
+ ", who all tell the same story of this "
+ "{7} {8}, exactly corresponding to the {9} of the legend."
, part[0], part[1], part[2], part[3], part[4], part[5]
, part[6], part[7], part[8], part[9]);
}
【问题讨论】:
-
看起来您想要使用对象而不是数组。 stackoverflow.com/questions/14747095/best-way-to-create-object
-
另一件事:为什么要让播放器类静态?你显然有一个真正的玩家,所以你最终可以做
Player myPlayer = new Player();并从那个实例中工作。和你的故事一样。不是您需要,我刚刚发现最好不要将所有内容都设为静态。 -
我什至不确定我是否会称它为 Person。一个更好的名字可能是像 MadLibSentence。然后 MadLibSentence 的一个实例可以有它自己的字符串集合(名词、形容词等)。 MadLibSentence 可以有一个名为 GetInput 的方法,该方法循环遍历字符串集合以获取每个字符串的输入。