C# 方法中重写时的数组参数不';不要在它之外改变
我有一个带有字符串数组的参数的方法。在函数中,我用另一个数组覆盖它时,它不会在它之外更改(如果我正确理解数组是通过引用传递的) 我有一个方法如下所示:C# 方法中重写时的数组参数不';不要在它之外改变,c#,.net,C#,.net,我有一个带有字符串数组的参数的方法。在函数中,我用另一个数组覆盖它时,它不会在它之外更改(如果我正确理解数组是通过引用传递的) 我有一个方法如下所示: static void Method(string word, string[] tab) { string [] tab1; [..] tab = tab1; // tab changes to tab1 } static void Main(string[
static void Method(string word, string[] tab)
{
string [] tab1;
[..]
tab = tab1; // tab changes to tab1
}
static void Main(string[] args)
{
string[] tab = { "", "", "", "", "", "", "", "", "", "" };
Method("443", tab);
//and here tab does not change like I though it would.
}
您需要通过引用传递它:
static void Method(string word, ref string[] tab)
{
string [] tab1;
[..]
tab = tab1; // tab changes to tab1
}
static void Main(string[] args)
{
string[] tab = { "", "", "", "", "", "", "", "", "", "" };
Method("443", ref tab);
//and here tab does not change like I though it would.
}
说明:是的,数组是引用对象,但默认值传递了此引用,因此您可以将其内容更改为outter范围。但是参数(选项卡)仅保存此引用的副本,因为此引用是通过值传递的。如果要直接修改传递参数的引用以引用其他对象,则需要使用ref
关键字
如果要避免使用ref
关键字,则需要返回新数组,并在Main
方法中使用它
static string[] Method(string word, string[] tab)
{
string [] tab1;
[..]
return tab1;
}
static void Main(string[] args)
{
string[] tab = { "", "", "", "", "", "", "", "", "", "" };
tab = Method("443",
}
更好的设计是:
static string[] Method(string word, string[] tab)
{
string [] tab1;
[..]
return tab1;
}
static void Main(string[] args)
{
string[] tab = { "", "", "", "", "", "", "", "", "", "" };
tab = Method("443", tab);
}
将
tab
aref
。您不“覆盖”它,而是“重新分配”它。术语很重要。问题是:您真的需要重新分配数组吗?您不能修改原始数组,或者更好地返回一个新数组吗?说明:该数组是通过值作为引用传递的。不是“通过引用”。有了下面托斯的答案,你就可以一个接一个地传递引用。这正是你想要做的。不,他们不需要,这是一种选择。另一个更干净的选项是返回一个新数组。这与按值传递的引用对象(您可以更改对象对调用方可见的内容)和作为ref参数传递的引用对象(您可以更改它以引用调用方可见的其他对象)有区别。所以不,数组不是通过引用传递的,而是作为引用对象,您可以更改内容。