class A
{
public int m_a;
}
void fun(ref int a)
{
...
}
fun(ref new A().m_a);
在乐趣中,“ref int a”如何在乐趣返回之前防止对象(新 A())被回收?
<example 0>
using System;
class A
{
public int m_a;
~A()
{
Console.WriteLine("~A()");
}
}
class Program
{
static void fun(ref int a)
{
Console.WriteLine("Begin<<<<<<<<<<<<<<");
a++;
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("End>>>>>>>>>>>>>>>>>");
}
static void Main(string[] args)
{
fun(ref new A().m_a);
Console.WriteLine("Over");
}
}
output:
Begin<<<<<<<<<<<<<<
~A()
End>>>>>>>>>>>>>>>>>
Over
<example 1>
using System;
class A
{
public int m_a;
~A()
{
Console.WriteLine("~A()");
}
}
class Program
{
static void fun(ref int a)
{
Console.WriteLine("Begin<<<<<<<<<<<<<<");
a++;
GC.Collect();
GC.WaitForPendingFinalizers();
//add a code
a++;
Console.WriteLine("End>>>>>>>>>>>>>>>>>");
}
static void Main(string[] args)
{
fun(ref new A().m_a);
Console.WriteLine("Over");
}
}
output:
Begin<<<<<<<<<<<<<<
End>>>>>>>>>>>>>>>>>
Over
~A()
请在 VS 中按发布模式构建。我查看ASM代码,只加了两行:
a++;
0000002f mov eax,dword ptr [ebp-4]
00000032 inc dword ptr [eax]
两个示例之间的其他部分相同。GC 如何确保变量 a 在机器代码中不再有用?