gpt4 book ai didi

c# - 为什么不能通过其他函数调整数组大小?

转载 作者:太空宇宙 更新时间:2023-11-03 20:59:52 25 4
gpt4 key购买 nike

根据MSDN,如果所有数组都是引用类型,那么为什么在给定的示例代码中,改变数组的大小必须使用关键字ref?谢谢!

class Program
{
static void Main(string[] args)
{
int[] test1 = { 1, 2, 3, 4 };
ResizeArray1(test1);
Console.WriteLine("Size 1 new = " + test1.Length); // Size 1 new = 4 ??

int[] test2 = { 1, 2, 3, 4 };
ResizeArray2(ref test2);
Console.WriteLine("Size 2 new = " + test2.Length); // Size 2 new = 8

Console.ReadKey();
}

static void ResizeArray1(int[] arr)
{
Array.Resize(ref arr, 8);
}

static void ResizeArray2(ref int[] arr)
{
Array.Resize(ref arr, 8);
}
}

最佳答案

if all arrays are reference type, then why in the given sample code, to change the size of the array must to use the keyword ref?

很简单,因为 Array.Resize 分配了一个新数组。然后它将现有元素值复制到新数组。因此,为确保更改会影响首先传递给 Array.Resize 的参数,我们必须使用 ref。这也是因为,默认情况下,所有参数都是按值传递的,无论它是值类型还是引用类型。

关于c# - 为什么不能通过其他函数调整数组大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46621356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com