我正在用 C# 构建一个控制台应用程序,我有一些变量在程序开始时定义,然后在调用方法后立即定义。该方法引用这些变量,因为它更改了其中一些变量。在我调用使用这些变量的方法之后不久,它使用原始定义,而不是先前方法中定义的定义。
这些是与问题相关的代码片段:
string foregroundColor = "White";
string backgroundColor = "Black";
testMap1(ref map, foregroundColor, backgroundColor);
static void testMap1(ref string[,] map, string foregroundColor, string backgroundColor)
{
resetMap(ref map, foregroundColor, backgroundColor);
foregroundColor = "Red";
backgroundColor = "Black";
static void resetMap(ref string[,] map, string foregroundColor, string backgroundColor)
{
foregroundColor = "White";
backgroundColor = "Black";
static void displayPosition2(ref string[,] map, int[] place, string foregroundColor, string backgroundColor)
{
if (foregroundColor == "Red")
{
Console.ForegroundColor = ConsoleColor.Red;
}
else if (foregroundColor == "Green")
{
Console.ForegroundColor = ConsoleColor.Green;
}
else if (foregroundColor == "Yellow")
{
Console.ForegroundColor = ConsoleColor.Yellow;
}
else if (foregroundColor == "Magenta")
{
Console.ForegroundColor = ConsoleColor.Magenta;
}
else if (foregroundColor == "DarkGreen")
{
Console.ForegroundColor = ConsoleColor.DarkGreen;
}
else if (foregroundColor == "Black")
{
Console.ForegroundColor = ConsoleColor.Black;
}
else if (foregroundColor == "Blue")
{
Console.ForegroundColor = ConsoleColor.Blue;
}
else if (foregroundColor == "Cyan")
{
Console.ForegroundColor = ConsoleColor.Cyan;
}
else if (foregroundColor == "DarkBlue")
{
Console.ForegroundColor = ConsoleColor.DarkBlue;
}
else if (foregroundColor == "DarkCyan")
{
Console.ForegroundColor = ConsoleColor.DarkCyan;
}
else if (foregroundColor == "DarkGrey")
{
Console.ForegroundColor = ConsoleColor.DarkGray;
}
else if (foregroundColor == "DarkMagenta")
{
Console.ForegroundColor = ConsoleColor.DarkMagenta;
}
else if (foregroundColor == "DarkRed")
{
Console.ForegroundColor = ConsoleColor.DarkRed;
}
else if (foregroundColor == "DarkYellow")
{
Console.ForegroundColor = ConsoleColor.DarkYellow;
}
else if (foregroundColor == "Gray")
{
Console.ForegroundColor = ConsoleColor.Gray;
}
else
{
Console.ForegroundColor = ConsoleColor.White;
}
此后应该输出红色文本,但输出白色,经过几次测试,问题出在displayposition2方法中使用的第一个定义。 我想知道为什么这没有按预期工作,我在现实生活中与之交谈过的每个人都说它应该有效。
“在 C# 中,字符串是不可变的,引用 MS 这篇文章“字符串对象是不可变的:它们在创建后就无法更改。所有看似修改字符串的 String 方法和 C# 运算符实际上都会在新字符串对象中返回结果。” https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/ #字符串的不变性