首页 > 解决方案 > 跨类访问方法

问题描述

我希望能够从“AtCommand”类访问我的“Uart”类中的方法。即 AT 命令类通过串行端口向调制解调器发送和从调制解调器接收命令。我无法弄清楚为什么 Uart 中的方法在“AtCommand”中不可用,但是如果我尝试从主窗体访问它们,它们是可用的。

这是两个类的代码,注意:在 GsmPort.Write 下有弯曲的红线,并警告它在当前上下文中不可用(所以我假设范围问题)。

using System.IO.Ports;
namespace ClassLessons
{
    class Uart
    {
        public bool Connected { get; set; }
        public bool DataInBuffer { get; set; }
        public string RxData;

    SerialPort port = new SerialPort();

    public Uart()
    {
        this.port.PortName = Properties.Settings.Default.PortName;
        this.DataInBuffer = false;
        this.RxData = "";
        this.port.BaudRate = 115200;
        this.port.ReadTimeout = 500;
        this.port.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
        Connected = false;
        try
        {
            if (!port.IsOpen)
            {
                port.Open();
                Connected = true;
            }
        }
        catch { }
    }

    private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            string data = this.port.ReadLine();
            RxData = data;
            DataInBuffer = true;
        }
        catch
        {

        }
    }

    public void Write(string message)
    {
        this.port.WriteLine(message);
    }


}

} }

和 AtCommand :

namespace ClassLessons
{
    class AtCommand
    {
        Uart GsmPort = new Uart();
        GsmPort.Write("Test");
    }
}

标签: c#class

解决方案


您的端口字段是私有的:

改变:

SerialPort port = new SerialPort();

至:

public SerialPort port = new SerialPort();

它将在其他课程中公开访问。


推荐阅读