提问者:小点点

c#为什么我使用类获得相同的输出?


我写了一段代码,对给定的输入进行排序,但在返回排序后的输入后,它将始终返回相同的输出。我正在使用创建控制台应用程序。Visual Studio中的NET 5.0(当前版本)。

当我输入“Car-Apple-Banana”时,它会按单词排序。排序()

之后,我打印出原始输入,但它似乎也被排序。我不知道为什么,因为我从不分类。

当输入为:“汽车苹果香蕉”

我现在得到的输出是:

苹果香蕉车

苹果香蕉车

虽然需要:

苹果香蕉车

汽车苹果香蕉

以下是主要代码:

using System;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;

namespace _10_Words
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] input_1 = Console.ReadLine().Split(' ');
            Words words = new Words(input_1);

            Console.WriteLine(words.Sorted());
            Console.WriteLine(words.Normal());
        }
    }
}

以下是课程代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _10_Words
{
    class Words
    {
        public string[] Output { get; set; }

        public Words(string[] input)
        {
            Output = input;
        }

        public string Sorted()
        {
            string[] sorted = Output;

            Array.Sort(sorted);

            string sorted_array = string.Join(" ", sorted);
            return Convert.ToString(sorted_array);
        }

        public string Normal()
        {
            string[] normal = Output;

            string normal_output = string.Join(" ", normal);
            return Convert.ToString(normal_output);
        }
    }
}

共3个答案

匿名用户

string[] sorted = Output;

Array.Sort(sorted);

当你调用Array.排序,这将修改您传递给它的数组。因为数组是通过引用传递的,所以sortedOutput引用相同的数组,该数组得到排序。

换句话说,当您对元素进行排序时,您正在更改输出。

最简单的解决方法是确保您创建一个新数组,其元素与旧数组相同:

// Don't forget to include this at the top of the file
using System.Linq;

string[] sorted = Output.ToArray();

Array.Sort(sorted);

另一个解决方案是将排序更改为不改变输入数组的方法,并返回一个新的(排序的)数组:

// Don't forget to include this at the top of the file
using System.Linq;

string[] sorted = Output.OrderBy(x => x).ToArray();

这两种解决方案都使用LINQ,这使得数组(和列表)操作更易于读取(IMHO)。

匿名用户

你似乎认为这条线

string[] sorted = Output;

将输入复制到输出,然后对输出进行排序,同时保持输入不变。

事实并非如此。

数组是引用类型。因此,当您将一个数组(如Output)分配给另一个数组变量(如sorted)时,sortedOutput将引用相同的数组。

如果需要副本,则必须迭代元素或使用辅助方法,例如Array。复制

sorted = new string[Output.Length];
Array.Copy(Output, sorted, Output.Length);

匿名用户

当你写的时候

string[] sorted = Output;

您将数组输出的引用分配给排序,然后使用

Array.Sort(sorted);

但由于排序只是对输出的引用,所以实际上是对输出进行排序。更好的方法是只打印原始数组,然后对其进行排序,然后打印。