我不明白为什么当我更改“copy_of_digits”数组时,“digits”和“parse_result”数组也会更改?我查看了一些关于按引用传递和按值传递的在线帮助,其中写到在 C# 中按值传递是默认值,并且您必须使用“ref”通过引用传递。我认为这里发生的是数组是通过引用而不是值传递的,但我不明白为什么以及如何修复它。任何帮助,将不胜感激!
namespace TestWithArrays
{
class Program
{
public static void Main()
{
Console.WriteLine("Please enter 2 digits:");
string user_input = Console.ReadLine();
int[] parse_result = Parse(user_input);
int[] multiply_by_two_result = MultiplyByTwo(parse_result);
Console.WriteLine("The End...");
Console.ReadLine();
}
public static int[] Parse(string user_input)
{
int[] digits = new int [2];
digits[0] = Int32.Parse(user_input.Substring(0,1));
digits[1] = Int32.Parse(user_input.Substring(1,1));
return digits;
}
public static int[] MultiplyByTwo(int[] digits)
{
int[] copy_of_digits = new int [2];
copy_of_digits = digits;
Console.WriteLine("´digits´ array before copy has been modified: " + string.Join(string.Empty, digits));
copy_of_digits[0] = copy_of_digits[0] * 2;
copy_of_digits[1] = copy_of_digits[1] * 2 ;
Console.WriteLine("´digits´ array after copy has been modified: " + string.Join(string.Empty, digits));
Console.WriteLine("´parse_result´ after copy has been modified: " + string.Join(string.Empty, digits));
return copy_of_digits;
}
}
}