我有一个类,一次只能有一个实例。它本质上是一个单例,当没有外部引用被保存时,它会被销毁,当您稍后需要新的引用时,它会被重新实例化。
private static readonly WeakReference<Foo> weakInstance = new WeakReference<Foo>(null);
上面代码的原因是因为我有原生的 iOS 回调(必须是静态函数),但需要将数据传递到当前实例。
tl;dr 将 WeakReference 初始化为 null 并稍后设置目标是否安全?这是代码味道吗?
编辑: 正如 @smolchanovsky 指出的,当我需要设置弱引用时,我可以实例化它。结果是:
if (weakInstance == null)
{
weakInstance = new WeakReference<Foo>(this);
}
else
{
weakInstance.SetTarget(this);
}
或
// Overwrite the existing WeakReference object
weakInstance = new WeakReference<Foo>(this);
有理由选择其中一个而不是另一个吗?
请您参考如下方法:
为什么不使用这个?
public sealed class Singleton
{
private static WeakReference<Singleton> weakInstance;
public WeakReference<Singleton> Instance
{
get
{
if (weakInstance == null)
weakInstance = new WeakReference<Singleton>(this);
else
weakInstance.SetTarget(this);
return weakInstance;
}
}
}
请注意,这不是线程安全的解决方案。

