Sharing a class between multiple forms

前端 未结 3 754
星月不相逢
星月不相逢 2021-01-23 05:39

I need help figuring this question out. I\'ve tried searching and I think I might have found a solution using a Singleton Design pattern, but want to make sure.

I have a

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-23 06:10

    Alternative to @Luiggi's solution, here's one a bit more thread conscience:

    public sealed class SerialPort
    {
      private static volatile SerialPort instance;
      private static object threadLock = new Object();
    
      /// Retrieve an instance of SerialPort
      public static SerialPort Instance
      {
        get
        {
          if (SerialPort.instance == null)
          {
            lock (SerialPort.threadLock)
            {
              if (SerialPort.instance == null)
              {
                SerialPort.instance == new Serialport();
              }
            }
          }
          return SerialPort.instance;
        }
      }
    
      private SerialPort(){}
    }
    

    Then, in practice:

    SerialPort sp = SerialPort.Instance;
    sp.MyMethod(...);
    

    More information on this Singleton pattern.

提交回复
热议问题