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


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

查看所有标签

猜你喜欢:

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

未来版图

未来版图

麻省理工科技评论 / 人民邮电出版社 / 2018-5-1 / CNY 69.80

《麻省理工科技评论》作为世界上历史悠久、影响力极大的技术商业类杂志,每年都会依据公司的科技领军能力和商业敏感度这两个必要条件,从全球范围内选取50家未来可能会成为行业主导的聪明公司。 这些聪明公司,并非都是行业巨头,甚至专利数量、公司所在地以及资金规模都不在考察范围内。 这些公司是“高精尖科技创新”与“能够保证公司利益* 大化的商业模式”的完 美融合。无论公办私营,无关规模大小,这些遍布全球......一起来看看 《未来版图》 这本书的介绍吧!

SHA 加密
SHA 加密

SHA 加密工具

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

Markdown 在线编辑器

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

UNIX 时间戳转换