在多个表单之间共享一个类 [英] Sharing a class between multiple forms

查看:21
本文介绍了在多个表单之间共享一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助来解决这个问题.我试过搜索,我想我可能已经找到了使用单例设计模式的解决方案,但我想确定一下.

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.

我有一个用 Visual C# 编写的 Windows 窗体应用程序.我正在编写一个 SerialPort 类,因此它可以通过所有表单共享(我不需要多个串行端口实例).这是为了将逻辑与 GUI 分开.所有表单都可以对SerialPort类进行波特率、写入、读取等各种更改.

I have a Windows forms app I am writing in Visual C#. I am writing a SerialPort class so it can be shared via all the forms (I don't need multiple serial port instances). This is to separate the logic from the GUI. All forms can make various changes to SerialPort class such as baud rate, write, read, etc.

实施此解决方案的最佳方法是什么?我是 OOP 的新手,所以任何关于阅读的建议都会很棒.

What is the best way to implement this solution? I'm new to OOP so any recommendations on readings would be great.

推荐答案

替代@Luiggi 的解决方案,这里有一个多一点的良心:

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();

  /// <summary>Retrieve an instance of SerialPort</summary>
  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(){}
}

然后,在实践中:

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

有关此单例模式的更多信息.

这篇关于在多个表单之间共享一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆