字符串值在 Class 中保持不变,但在外部是否正确?

String Value stays the same in Class but is correct outside?

我正在编写 "Text Adventure Game" 作为控制台应用程序。游戏开始时,我向玩家询问他的 PlayerName 并将其保存在 public 变量中。这现在将用于个性化故事情节的几个部分,并且工作完美。

然而,在某些时候,玩家会被问到是否愿意更改他们的名字。如果他们这样做,我从他们那里得到它并覆盖现有的字符串。

这就是问题所在:如果我继续使用原始数组值(其中填充了旧 PlayerName 值),我会看到旧名称仍然存在。但是如果我写出 PlayerName 变量本身的值,它就会有新的值。

如果我做对了,这意味着在我的数组中,值保持不变,即使 我覆盖了最初创建它的变量的值,但如果我在我的代码中使用 varibalbe 本身,它就会具有新值。

例如:

我的第一次尝试是简单地覆盖现有的变量:

Game.Playername = Console.ReadLine();

我的第二次尝试是创建一个带有字符串输入的方法,该方法将覆盖变量:

Game.NameChange(Console.ReadLine());

即使 PlayerName 字段具有新值,这两者都会导致数组仍然包含错误(旧)值,这意味着该方法基本上可以正常工作,但数组不会收到新值.

游戏流程阶段"Name Change":

else if(Game.TempDec == "n")
{
    Console.WriteLine("Enter Name:\n");
    Game.NameChange(Console.ReadLine());
    Dialoge.Narrator(StoryLine.Seq02[11]);
}

修改玩家名字的方法:

public static void NameChange(string name)
{
    PlayerName = name;
}

字符串数组定义:

public static string[] Seq02=
{
    "...", "...", "...", "...", "...", 
    "...", "...", "...", "...", "...", "...", 
    "Your Name is " + Game.PlayerName + "...", //(Index 11)
    "...", "...",
}

我做错了什么?我缺少什么?

通过写作

public static string[] Sequence =
{
    "...",
    "Your Name is " + Game.PlayerName + "..."; //(Index 11)
    "..."
}

您正在修复 Sequence[11] 中字符串的值。如果您更改 PlayerName,该值将不会更改,因为您正在使用当时的值创建一个新字符串。

偶以为 is correct, I would like to point out, that you can achieve specified behavior by using string.Format() method。所以每次你想打印当前玩家名称的字符串时,你可以使用 string.Format(Seq02[11], Game.PlayerName) ,其中 Seq02[11] = "Your Name is {0} ..."{0} 将被当前玩家名称替换。还可以考虑创建将玩家名称插入作为参数传递的每个字符串的方法,例如:

public string InsertPlayerName(string sentence){
   return string.Format(sentence, Game.PlayerName);
}

此方法用当前玩家名称替换句子参数中出现的每个 {0}