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


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

查看所有标签

猜你喜欢:

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

嵌入式系统软件设计中的常用算法

嵌入式系统软件设计中的常用算法

周航慈 / 2010-1 / 24.00元

《嵌入式系统软件设计中的常用算法》根据嵌入式系统软件设计需要的常用算法知识编写而成。基本内容有:线性方程组求解、代数插值和曲线拟合、数值积分、能谱处理、数字滤波、数理统计、自动控制、数据排序、数据压缩和检错纠错等常用算法。从嵌入式系统的实际应用出发,用通俗易懂的语言代替枯燥难懂的数学推导,使读者能在比较轻松的条件下学到最基本的常用算法,并为继续学习其他算法打下基础。 《嵌入式系统软件设计中的......一起来看看 《嵌入式系统软件设计中的常用算法》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具