用空值初始化 WeakReference 可以吗?
Is it okay to initialise WeakReference with a null value?
我有一个 class,它一次只会有一个实例。它本质上是一个单例,当没有外部引用被保留时被销毁,并在您以后需要新引用时重新实例化。
private static readonly WeakReference<Foo> weakInstance = new WeakReference<Foo>(null);
上面代码的原因是因为我有原生iOS回调(必须是静态函数)但需要将数据传递给当前实例。
tl;dr 将 WeakReference
初始化为空并稍后设置目标是否安全?这是代码味道吗?
编辑:
正如@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;
}
}
}
请注意,这不是线程安全的解决方案。
我有一个 class,它一次只会有一个实例。它本质上是一个单例,当没有外部引用被保留时被销毁,并在您以后需要新引用时重新实例化。
private static readonly WeakReference<Foo> weakInstance = new WeakReference<Foo>(null);
上面代码的原因是因为我有原生iOS回调(必须是静态函数)但需要将数据传递给当前实例。
tl;dr 将 WeakReference
初始化为空并稍后设置目标是否安全?这是代码味道吗?
编辑: 正如@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;
}
}
}
请注意,这不是线程安全的解决方案。