我有一个实现单例模式的类A
并包含object obj
:
public sealed class A
{
static A instance=null;
static readonly object padlock = new object();
public object obj;
A()
{
AcquireObj();
}
public static A Instance
{
get
{
if (instance==null)
{
lock (padlock)
{
if (instance==null)
{
instance = new A();
}
}
}
return instance;
}
}
private void AcquireObj()
{
obj = new object();
}
}
现在我有了另一个B类,我需要保留A.obj对象的实例,直到它还活着。
public class B
{
// once class A was instantiated, class B should have public A.obj
// field available to share.
// what is the best way/practice of putting obj here?
}
谢谢。
答案 0 :(得分:2)
就这样:
class B
{
public object obj
{
get
{
return A.Instance.obj;
}
}
}
如果这是第一次有人接触A.Instance
,这将初始化它。在后续调用中,它将重用A
的相同实例。