需要从不同的类别访问串行端口



我正在使用设计器在 C# 中生成的串行端口对象(非静态(。

我需要能够从不同类中的静态方法访问它(我知道这是一种不好的做法,但这是我继承的(

端口访问使用以下代码。

    public bool Read_Board_Port()
    {
        byte[] bData = new byte[256];
        string message;
        bool sucess = false;
        try
        {
            if (!(serialBoardPort.IsOpen == true))
                Connect_To_Board(Globals.BoardportName, Globals.BoardbaudRate, Globals.Boardparity, Globals.BoardstopBits, Globals.BoarddataBits);
           if(CMDDirect || Globals.HostCommandString)
            {
                serialBoardPort.ReadTimeout = 1000; // Timeout if no answer from the port.
                message = serialBoardPort.ReadLine();
                Globals.RXBoardBuff = Encoding.UTF8.GetBytes(message);
                Write_To_Console_Dr(message);
                sucess = true;
            }
           else
            {
                serialBoardPort.Read(Globals.RXBoardBuff, 0, Constants.RXBOARDBUFFSIZE);
                if (Check_Command_Correct(Globals.RXBoardBuff, Globals.CommandOut))
                    sucess = true;
                else
                {
                    Write_Error_To_Console_Dr(Constants.ERRORDATAFROMBOARDPORT);
                    sucess = false;
                }
            }
        }
        catch
        {
            MessageBox.Show(Constants.ERRORNODATABOARPORT);
            sucess = false;
        }
        return sucess;
    }

如果我声明 new 将使用串行端口的不同实例,我需要使用已经打开的端口。

谢谢

正如@Matthew Spencer所说,您应该将串行端口作为参数传递给需要它的静态方法。首先在你的板类上创建一个方法,或者它的名字是什么,返回你的串行端口的实例。然后使用它来获取用于您提到的静态方法的串行端口。

这样的东西应该是你需要的。

public bool Read_Board_Port()
    {
        byte[] bData = new byte[256];
        string message;
        bool sucess = false;
        try
        {
            if (!(serialBoardPort.IsOpen == true))
                Connect_To_Board(Globals.BoardportName, Globals.BoardbaudRate, Globals.Boardparity, Globals.BoardstopBits, Globals.BoarddataBits);
           if(CMDDirect || Globals.HostCommandString)
            {
                serialBoardPort.ReadTimeout = 1000; // Timeout if no answer from the port.
                message = serialBoardPort.ReadLine();
                Globals.RXBoardBuff = Encoding.UTF8.GetBytes(message);
                Write_To_Console_Dr(message);
                sucess = true;
            }
           else
            {
                serialBoardPort.Read(Globals.RXBoardBuff, 0, Constants.RXBOARDBUFFSIZE);
                if (Check_Command_Correct(Globals.RXBoardBuff, Globals.CommandOut))
                    sucess = true;
                else
                {
                    Write_Error_To_Console_Dr(Constants.ERRORDATAFROMBOARDPORT);
                    sucess = false;
                }
            }
        }
        catch
        {
            MessageBox.Show(Constants.ERRORNODATABOARPORT);
            sucess = false;
        }
        return sucess;
    }
// since serialBoardPort seems to be a globally declared variable
public SerialPort GetInstance()
{
    return serialBoardPort;
}
// Let's name your class as board..
// on somewhere in your app code:
Board board = // GetValue 
SerialPort boardSerialPort = board.GetInstance();
ClassXXX.StaticMethodNeedsPort(boardSerialPort); // pass your serial port to the static method

更新:因为正如提问者所说,存在一些误解。

我建议使用 IoC 容器,在此处阅读更多内容

这是我使用的。通常,这已经是MVVM Cross等框架的一部分。

法典:

public class Core
{
    private static readonly Core instance = new Core();
    private Dictionary<Type, object> container;
    private Core()
    {
        container = new Dictionary<Type, object>();
    }
    public void RegisterSingleton<T>(T value) where T : class
    {
        Type type = typeof(T);
        if (!container.ContainsKey(type))
            container.Add(type, value);
    }
    public T GetSingleton<T>() where T : class
    {
        Type type = typeof(T);
        if (container.ContainsKey(type))
            return (T)container[type];
        else
            throw new Exception("Singleton instance not registered.");
    }
    public void RemoveSingleton<T>() where T : class
    {
        Type type = typeof(T);
        if (container.ContainsKey(type))
            container.Remove(type);
    }
    public void ClearSingletons()
    {
        container.Clear();
    }
    public static Core Instance
    {
        get { return instance; }
    }
}

加载应用程序时,添加以下行:

Core.Instance.ClearSingletons();

如果它在加载时已经有一个端口,因为它是由 C# 自动生成的,只需注册实例。

Core.Instance.RegisterSingleton(MySerialPortObject); // Or class. Can be object

在应用程序方面,当您需要端口时,只需像这样获取其实例...

SerialPort _myPort = Core.Instance.GetSingleton<X>(); // Where X value is the type of your registered object. If you are registering a SerialPort then replace X with SerialPort.

您可以在任何您喜欢的地方获取端口的实例。当我使用它时,我通常会注册接口的实现,以便我可以像

IFileHandler _fileHandler = Core.Instance.GetSingleton<IFileHandler>() // Where I registered the class that implements IFileHandler upon the startup of my application

对不起,答案很长。

最新更新