我有这个代码:
基本上我正在尝试演示使用c#终结器并制作一个不能死的对象,我称之为Zombie.现在,通常这个演示工作得很好,但今天我尝试使用与对象初始化器相同的代码而不是仅仅分配给属性(在这种情况下为Name).我注意到有区别.即使终结器永远不会被调用,即使我正在尽最大努力使垃圾收集器完成它的工作.
有人可以解释这个区别,还是我在C#编译器中发现了一个错误?
(我在Win7x64上使用VS2010 SP1中的C#4)
谢谢.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Zombie
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Main thread: " + Thread.CurrentThread.ManagedThreadId);
// case 1: this is where the problem is located.
Zombie z = new Zombie { Name = "Guy" }; // object initializer syntax makes that the finalizer is not called.
// case 2: this is not causing a problem. The finalizer gets called.
//Zombie z = new …Run Code Online (Sandbox Code Playgroud)