c# - 跨类访问方法
问题描述
我希望能够从“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");
}
}
解决方案
您的端口字段是私有的:
改变:
SerialPort port = new SerialPort();
至:
public SerialPort port = new SerialPort();
它将在其他课程中公开访问。
推荐阅读
- r - 基于多列值的复杂 case_when() 语句 (dplyr)
- python - 有没有办法使用 pygame 播放原始 8 位 PCM 数据?
- google-bigquery - 临时函数的 BigQuery LEFT OUT JOIN 错误?
- windows - 如何根据文件名自动创建文件夹并使用 .BAT 将文件移动到其文件夹中
- python - 如果 Scipy.spatial.distance.cdist 使用双 for 循环,为什么它会很快?
- kubernetes - 在 Windows Server 2022 上运行 .NET 容器
- python - 在 Python 3 中使用 pyobjc-framework-Quartz
- url-rewriting - OVH 的 URL 重写
- linux - Vs code 嵌入式终端奇怪的颜色
- java - 如何在eclipse中使用extends重构多个类名?