我最近遇到了这篇SO 文章,并针对我的场景进行了调整,如下所示:
using System;
using System.Collections.Generic;
namespace ConsoleApplication18
{
class Program
{
static void Main(string[] args)
{
Manager mgr = new Manager();
var obj = new byte[1024];
var refContainer = new RefContainer();
refContainer.Target = obj;
obj = null;
mgr["abc"] = refContainer.Target;
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
Console.WriteLine(mgr["abc"] != null); // true (still ref'd by "obj")
refContainer = null;
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
Console.WriteLine(mgr["abc"] != null); // false (no remaining refs)
}
}
class RefContainer
{
public object Target { get; set; }
}
class Manager
{
Dictionary<string, WeakReference> refs =
new Dictionary<string, WeakReference>();
public object this[string key]
{
get
{
WeakReference wr;
if (refs.TryGetValue(key, out wr))
{
if (wr.IsAlive)
return wr.Target;
refs.Remove(key);
}
return null;
}
set
{
refs[key] = new WeakReference(value);
}
}
}
}
运行此程序会产生以下预期结果:
True
False
Press any key to continue . . .
但是改变这个:
var refContainer = new RefContainer();
refContainer.Target = obj;
为此(使用 Object Initializer 语法):
var refContainer = new RefContainer() { Target = obj };
给出以下输出:
True
True
Press any key to continue . . .
这里发生了什么?为什么引用的生命周期会因为使用 Object Initializer 而不同?