C# 传递 class 成员作为 ref 参数
C# passing class member as ref parameter
我不明白为什么可以将 class 实例成员作为 ref 参数传递给函数。
当函数正在执行时,垃圾回收可能会移动对象,从而使引用无效。
但这似乎是允许的并且有效。这是否意味着 "ref" 参数不仅仅是底层的本地指针?
class A
{
public int Value;
}
class Test
{
static void F(ref int value)
{
value = 7;
}
static void Main()
{
A obj = new A();
// obj can be moved by GC, so "ref obj.Value" cannot be a native pointer under the hood
F(ref obj.Value);
System.Console.WriteLine(obj.Value); // Prints 7
}
}
Does it mean "ref" parameters are more than just a native pointer under the hood?
是的,就是这个意思。如果它只是一个指针,他们会称它为指针而不是引用。相反,对于引用,GC 了解原始对象并正确跟踪事物,因此引用保留在对象中,并且在方法退出之前不会收集对象。
我不明白为什么可以将 class 实例成员作为 ref 参数传递给函数。
当函数正在执行时,垃圾回收可能会移动对象,从而使引用无效。
但这似乎是允许的并且有效。这是否意味着 "ref" 参数不仅仅是底层的本地指针?
class A
{
public int Value;
}
class Test
{
static void F(ref int value)
{
value = 7;
}
static void Main()
{
A obj = new A();
// obj can be moved by GC, so "ref obj.Value" cannot be a native pointer under the hood
F(ref obj.Value);
System.Console.WriteLine(obj.Value); // Prints 7
}
}
Does it mean "ref" parameters are more than just a native pointer under the hood?
是的,就是这个意思。如果它只是一个指针,他们会称它为指针而不是引用。相反,对于引用,GC 了解原始对象并正确跟踪事物,因此引用保留在对象中,并且在方法退出之前不会收集对象。