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

栏目: ASP.NET · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/27197988/array-sort-sorts-original-array-and-not-just-copy

此代码段来自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);
    }
}

sortedNames和行星都指向同一个数组.基本上两个变量都指向内存中的相同位置,因此当您在任一变量上调用Array.Sort时,对这两个变量都会反映对数组的更改.

由于C#中的数组是引用类型,因此sortedNames和行星都“指向”内存中的相同位置.

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

如果你想保持行星不变,可以使用创建一个全新的数组,然后使用Array.Copy用行星的内容填充新数组:

/* 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);

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

string[] sortedNames = planets.OrderBy(planet => planet).ToArray();

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

> Value types and Reference Types (MSDN)

> What is the difference between a reference type and value type in c#?

翻译自:https://stackoverflow.com/questions/27197988/array-sort-sorts-original-array-and-not-just-copy


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

A Byte of Python

A Byte of Python

Swaroop C H / Lulu Marketplace / 2008-10-1 / USD 27.98

'A Byte of Python' is a book on programming using the Python language. It serves as a tutorial or guide to the Python language for a beginner audience. If all you know about computers is how to save t......一起来看看 《A Byte of Python》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换