数组正在影响其他数组值C#

数组正在影响其他数组值C#,c#,arrays,sorting,windows-8,C#,Arrays,Sorting,Windows 8,我正在尝试获取初始数组的副本,然后尝试对该副本进行排序。但是,当我使用Array.Sort()函数时,我的第一个数组也会继续被排序,但我想保留它。我试着在计分表上删除新的声明,但这并没有影响结果 还有,是否有办法将数组中未使用的变量保持为null?(如果我没有使用它的所有部分,我会在数组的开头得到一堆0) 我正在运行Windows 8.1 Pro的系统上使用Visual Studio Express 2012 for Windows 8。表达式scoreScope=scores将句柄复制到数组

我正在尝试获取初始数组的副本,然后尝试对该副本进行排序。但是,当我使用Array.Sort()函数时,我的第一个数组也会继续被排序,但我想保留它。我试着在计分表上删除新的声明,但这并没有影响结果

还有,是否有办法将数组中未使用的变量保持为null?(如果我没有使用它的所有部分,我会在数组的开头得到一堆0)


我正在运行Windows 8.1 Pro的系统上使用Visual Studio Express 2012 for Windows 8。

表达式
scoreScope=scores将句柄复制到数组

如果要创建数组项的副本,应将该行更改为:
scores.copyTo(scorescopy,0)

您仍然需要确保
scorecopy
有足够的空间存放物品。
所以您还需要这个表达式:
static int[]scorescopy=new int[scores.Length]

现在,您的代码应该是这样的:

static int[] scores = new int[100];
static int[] scorescopy;
public static int orderscores()
{
   scorescopy = scores;
    Array.Sort(scorescopy);
    int sortingtoolb = 0;
    return 0;
}

表达式
scoreScope=分数将句柄复制到数组

如果要创建数组项的副本,应将该行更改为:
scores.copyTo(scorescopy,0)

您仍然需要确保
scorecopy
有足够的空间存放物品。
所以您还需要这个表达式:
static int[]scorescopy=new int[scores.Length]

现在,您的代码应该是这样的:

static int[] scores = new int[100];
static int[] scorescopy;
public static int orderscores()
{
   scorescopy = scores;
    Array.Sort(scorescopy);
    int sortingtoolb = 0;
    return 0;
}

如果您获得指向同一数组的指针,则需要克隆:

static int[] scores = new int[100];
static int[] scorescopy = new int[scores.Length];

public static int orderscores()
{
    scores.copyTo(scorescopy,0);
    Array.Sort(scorescopy);
    int sortingtoolb = 0;
    return 0;
}

如果您获得指向同一数组的指针,则需要克隆:

static int[] scores = new int[100];
static int[] scorescopy = new int[scores.Length];

public static int orderscores()
{
    scores.copyTo(scorescopy,0);
    Array.Sort(scorescopy);
    int sortingtoolb = 0;
    return 0;
}

数组在指定时,仅将引用复制到内存中的同一数组。您需要实际复制这些值才能使其工作:

scorescopy = (int [])scores.Clone();
请注意,您可以通过以下方式在不使用LINQ的情况下执行此操作:

public static int orderscores()
{
    scorescopy = scores.ToArray(); // Using LINQ to "cheat" and make the copy simple
    Array.Sort(scorescopy);
    int sortingtoolb = 0;
    return 0;
}

数组在指定时,仅将引用复制到内存中的同一数组。您需要实际复制这些值才能使其工作:

scorescopy = (int [])scores.Clone();
请注意,您可以通过以下方式在不使用LINQ的情况下执行此操作:

public static int orderscores()
{
    scorescopy = scores.ToArray(); // Using LINQ to "cheat" and make the copy simple
    Array.Sort(scorescopy);
    int sortingtoolb = 0;
    return 0;
}

您需要了解引用类型和值类型之间的区别,特别是这对赋值意味着什么。大多数C#书的第一章都会涉及到这一点。实际上,我的书的第十章已经涉及到了这一点。。。但由于我忘记了这叫做克隆,我无法通过它和互联网自己找到答案。你需要理解引用类型和值类型之间的区别,特别是这对赋值意味着什么。大多数C#书的第一章都会涉及到这一点。实际上,我的书的第十章已经涉及到了这一点。。。但是因为我忘记了它叫克隆,我没能通过它和互联网自己找到答案。@ReedCopsey是的,它是有效的。除此之外,它应该是克隆人()上的大写字母C@那就别光说它无效了。说什么不对。说它是无效的意味着它是完全不正确的。谢谢你提供了非常简单的解决方案!我忘记了克隆函数。@ReedCopsey是的,它是有效的C。除此之外,它应该是克隆人()上的大写字母C@那就别光说它无效了。说什么不对。说它是无效的意味着它是完全不正确的。谢谢你提供了非常简单的解决方案!我忘记了克隆功能。请注意,如果未首先分配
scoreScope
,这将引发异常。true-将尽快修复该异常:)请注意,如果未首先分配
scoreScope
,这将引发异常。true-将尽快修复该异常:)