0

我有一个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? 
}

谢谢你。

4

1 回答 1

2

就像这样:

class B
{
    public object obj
    {
        get
        {
            return A.Instance.obj;
        }
    }
}

如果这是第一次有人触摸A.Instance,这将初始化它。在后续调用中,它将重用A.

于 2013-09-03T18:33:12.730 回答