【发布时间】:2022-01-15 05:19:48
【问题描述】:
我编写了对给定输入进行排序的代码,但在返回排序后的输入后,它总是会返回相同的输出。我正在 Visual Studio 中使用 .NET 5.0(当前)创建控制台应用程序。
当我输入“Car Apple Banana”作为输入时,它会以 words.Sorted() 进行排序
之后我打印出原始输入,但它似乎也被排序了。我不知道为什么,因为我从不排序。
当输入为:“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);
}
}
}
【问题讨论】:
-
先尝试拨打
Normal()。您的Sorted()电话正在更改数组。 -
string[] sorted = Output没有复制 array,它只是将 reference 复制到数组中到一个新变量中。所以,是的,当您排序时,您正在对实际存在的一个数组进行排序。 -
@LarsTech ,我将向它添加更多不同的类,这样就无济于事了
-
@Damien_The_Unbeliever 如何让它复制实际的数组?
-
你必须使用 Array.Copy。检查 .NET 文档。