【发布时间】:2015-11-02 17:47:46
【问题描述】:
在这段小代码中,改变方法内部的二维数组会导致改变 main 方法中的变量。
这是什么原因,如何保护 main 方法中的变量保持不变?
using System;
namespace example
{
class Program
{
static void Main(string[] args)
{
string[,] string_variable = new string[1, 1];
string_variable[0, 0] = "unchanged";
Console.Write("Before calling the method string variable is {0}.\n", string_variable[0,0]);
Function(string_variable);
Console.Write("Why after calling the method string variable is {0}? I want it remain unchanged.\n", string_variable[0, 0]);
Console.ReadKey();
}
private static void Function(string [,] method_var)
{
method_var[0, 0] ="changed";
Console.Write("Inside the method string variable is {0}.\n", method_var[0, 0]);
}
}
}
最后这是程序输出:
Before calling the method string variable is unchanged.
Inside the method string variable is changed.
Why after calling the method string variable is changed? I want it remain unchanged.
编辑 1:我想到的一个问题是:还有哪些常见的编程语言没有这种问题?
编辑2:为了便于比较,我用字符串变量而不是数组编写了这个以某种方式相同的代码,并且输出符合预期并且很好:
using System;
namespace example
{
class Program
{
static void Main(string[] args)
{
string string_variable;
string_variable= "unchanged";
Console.Write("Before calling the method string variable is {0}.\n", string_variable);
Function(string_variable);
Console.Write("after calling the method string variable is {0} as expected.\n", string_variable);
Console.ReadKey();
}
private static void Function(string method_var)
{
method_var ="changed";
Console.Write("Inside the method string variable is {0}.\n", method_var);
}
}
}
这段代码的输出是:
Before calling the method string variable is unchanged.
Inside the method string variable is changed.
after calling the method string variable is unchanged as expected.
最后编辑:感谢大家的澄清,希望这对其他人有用。
【问题讨论】:
-
@MyUserName: 如果没有
ref或out关键字,您将永远无法更改传入参数的值(例如method_var = null不会更改@ 987654328@),但在 .NET 中,作为参数传递的引用类型对象的值是它的引用。没有关键字可以阻止您调用索引器或调用对象上可能更改其状态的方法。 -
您的基本问题是数组是变量的集合。变量可以改变;这就是为什么它们被称为变量。如果你不喜欢数组是变量的集合,那么不要使用数组。还有许多其他数据结构不是变量的集合。
-
至于您的更新:字符串不是变量的集合。字符串是字符值的集合,而不是字符变量的集合。同样,数组是变量的集合,变量可以改变。同样,如果您不想更改某些内容,不要使用变量集合。他们改变了!
-
我还注意到您的声明“更改方法内的二维数组会导致更改 main 方法中的变量。”完全是错误的。
string_variable的值没有改变。它是一个参考。它指的是一个变量的集合。该参考永远不会改变。 引用所指的变量发生变化。 -
这样想。您在一张纸上写下“MyUserName 的袜子抽屉”。你复印那张纸,然后交给朋友。朋友看了看他们的纸,走到指定的抽屉前,把袜子放在抽屉里。你的纸条变了吗?不。这张纸所指的袜子抽屉有变化吗?是的。 它应该是这样工作的。
标签: c# arrays multidimensional-array