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


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

查看所有标签

猜你喜欢:

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

Web标准之道

Web标准之道

阿一、棕熊、李战、丁学 / 人民邮电出版社 / 2009-8 / 35.00元

《Web标准之道:博客园精华集》由博客园知名博主联手打造,涉及Web标准、HTML/CSS、JavaScript、SEO优化等诸多领域,内容新颖,观点独特,妙语连珠。《Web标准之道:博客园精华集》并不是一本由代码和技巧堆积而成的集合,更多的是探讨了Web设计中若干理念和心得,其中多为经验之谈。无论对于从事Web前端设计的人士,还是对于那些从事Web后端编程的技术人员,《Web标准之道:博客园精华......一起来看看 《Web标准之道》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

SHA 加密
SHA 加密

SHA 加密工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具