Array.Sort()对原始数组进行排序,而不仅仅是复制

Bil*_*aro 8 c# arrays sorting

此代码段来自C#2010 for Dummies.令我困惑的是,当使用Array.Sort()方法时,我的数组副本(sortedNames)和原始数组(行星)都会被排序,即使它只调用sortedNames上的Sort方法.

第二个foreach循环引用哪个数组无关紧要,输出是相同的.

static void Main(string[] args)
{
    Console.WriteLine("The 5 planets closest to the sun, in order: ");
    string[] planets = new string[] { "Mercury","Venus", "Earth", "Mars", "Jupiter"};
    foreach (string planet in planets)
    {
        Console.WriteLine("\t" + planet);
    }
    Console.WriteLine("\nNow listed alphabetically: ");


    string[] sortedNames = planets;
    Array.Sort(sortedNames);

    foreach (string planet in planets)
    {
        Console.WriteLine("\t" + planet);
    }
}
Run Code Online (Sandbox Code Playgroud)

And*_*ker 20

二者sortedNamesplanets指代相同的阵列.基本上两个变量都指向内存中的相同位置,因此当您调用Array.Sort任一变量时,对这两个变量都会反映对数组的更改.

由于在C#数组引用类型,都sortedNamesplanets"点"到在存储器中的相同位置.

将此与值类型进行对比,后者将数据保存在自己的内存分配中,而不是指向内存中的另一个位置.

如果你想保持planets完整,你可以使用创建一个全新的数组,然后使用Array.Copy以下内容填充新数组planets:

/* Create a new array that's the same length as the one "planets" points to */
string[] sortedNames = new string[planets.Length];

/* Copy the elements of `planets` into `sortedNames` */
Array.Copy(planets, sortedNames, planets.Length);

/* Sort the new array instead of `planets` */
Array.Sort(sortedNames);
Run Code Online (Sandbox Code Playgroud)

或者,使用LINQ,您可以使用OrderByToArray创建一个新的有序数组:

string[] sortedNames = planets.OrderBy(planet => planet).ToArray();
Run Code Online (Sandbox Code Playgroud)

一些可能有助于值类型引用类型的资源: