【发布时间】:2018-01-13 17:19:36
【问题描述】:
为什么ArrayCalledWithOrderBy 不会改变原来传递的数组,而ArrayCalledWithSort 会?
编辑:至于建议重复的链接。一个链接中甚至没有 OrderBy,因此它显然不是重复的。另一个链接实际上是询问 OrderBy 和 Sort 之间哪个更好,而不是为什么不更改原始数组。
public static void ArrayCaller()
{
var arr = new string[] { "pink", "blue", "red", "black", "aqua" };
DisplayArray(arr, "Before method calls");
ArrayCalledWithOrderBy(arr);
DisplayArray(arr, "After method call using orderby");
ArrayCalledWithSort(arr);
DisplayArray(arr, "After method call using sort");
}
public static void ArrayCalledWithOrderBy(string[] arr)
{
// this does not change the original array in the calling method. Why not?
arr = (arr.OrderBy(i => i).ToArray());
DisplayArray(arr, "After orderby inside method");
}
public static void ArrayCalledWithSort(string[] arr)
{
// this changes the original array in the calling method.
// Because it is using the same reference?
// So the above code for orderby does not?
Array.Sort(arr);
DisplayArray(arr, "After sort inside method");
}
public static void DisplayArray(string[] arr, string msg)
{
for (int i=0; i<arr.Length; i++)
{
Console.Write($"{arr[i]} ");
}
Console.WriteLine($" - {msg}");
}
// OUTPUT
//pink blue red black aqua - Before method calls
//aqua black blue pink red - After orderby inside method
//pink blue red black aqua - After method call using orderby
//aqua black blue pink red - After sort inside method
//aqua black blue pink red - After method call using sort
【问题讨论】:
-
@NisargShah 不。这个问题询问为什么
ArrayCalledWithOrderBy中的覆盖arr数组不会更新ArrayCaller()中的arr数组。 This question 是关于字符串的传递,但可以很容易地更改为数组。 -
@NisargShah。看起来链接正在尝试确定哪个是更好的选择。我试图确定为什么一个改变了原始数组而另一个没有。
-
@NisargShah 首先不是重复的。很明显,OP 询问为什么更改
arr没有反映在ArrayCaller() -
@ColeJohnson 我不介意 Niki 同意你的看法。但从最初的措辞来看,这似乎是一个明显的重复。
-
从您的声明
arr = (arr.OrderBy(i => i).ToArray());,我推断您确实了解OrderBy()不会修改数组。如果不这样做,请参阅第二个标记的重复项。您似乎不理解的是,默认情况下,方法参数是按值传递的,对这些参数值的更改不会影响调用者的变量(如果有的话)。您需要使用ref或out来修改调用者的变量。有关详细信息,请参阅第一个标记的副本,包括它如何应用于您的确切情况(即使用数组)。