gpt4 book ai didi

c# - 通过 ref 和实例化新对象时的堆分配

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

假设我有以下代码:

var person = new Person();
Manipulate(ref person);

还有下面的方法:

public void Manipulate(ref Person pObject)
{
pObject = new Person();
}

在实例化一个新的 Person 对象时,Manipulate 方法是指向堆上的同一位置并在该位置创建 pObject,还是在堆上创建一个新位置?

最佳答案

答案在 Docs 中:

The storage location of the object is passed to the method as the value of the reference parameter. If you change the value in the storage location of the parameter (to point to a new object), you also change the storage location to which the caller refers.

为了清楚起见,请检查以下示例:

static int[] array = new int[] { 5 };

static void Main(string[] args)
{
var array2 = array;
ModifyRef(ref array2);

foreach (var item in array)
Console.WriteLine(item);
foreach (var item in array2)
Console.WriteLine(item);
}

private static void ModifyRef(ref int[] array)
{
array = new int[1];
array[0] = 10;
}

打印:

5
10

使通过引用传递的指针引用一个新对象并不意味着旧对象被替换。 array2 现在指向一个新的内存位置,但是 array 仍然指向内存中的同一个旧数组。

关于c# - 通过 ref 和实例化新对象时的堆分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38772726/

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