我是C#的新手,也是来自C的对象导向。
我的问题是我尝试创建一个可以同时从多个串行端口读取的程序。我得到了一个处理单个串口的程序。
目前我有一个静态功能,用于配置我想使用的8个串口。在这个静态函数中,我调用:
SerialPortToSetup.DataReceived + = new SerialDataReceivedEventHandler(SerialPortEventHandler);
此函数本身调用一个类来从串行端口读取数据并将其传回。如何在尝试维护抽象以获取以后添加更多SerialPort的可能性时,如何获取SerialPort发出的信息?
在代码存在状态中,我得到一个错误,因为flowmeter_data_array不是静态对象,因此无法调用,并且该函数不能非静态,因为设置事件处理程序的函数是静态的。
private static void SetupSerialPort(SerialPort SerialPortToSetup, ComboBox PortNameComboBox, ComboBox BaudRateComboBox)
{
SerialPortToSetup.BaudRate = Convert.ToInt32(BaudRateComboBox.Text);
SerialPortToSetup.DataReceived += new SerialDataReceivedEventHandler(SerialPortEventHandler);
SerialPortToSetup.PortName = PortNameComboBox.Text;
}
private static void SerialPortEventHandler(object sender, SerialDataReceivedEventArgs e)
{
data_array[data_array.Length] = SerialData.GetSerialData((SerialPort) sender);
}
到目前为止的课程如下所示
public static class SerialData
{
public static string GetSerialData(SerialPort SerialPortSent)
{
string data_string = string.Empty;
try
{
if (SerialPortSent.IsOpen)
{
data_string = SerialPortSent.ReadLine();
}
else
{
MessageBox.Show("Serial Port not open", "Read Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
data_string = "ABORT CODE";
}
}
catch (ArgumentNullException)
{
MessageBox.Show("Read Buffer = NULL", "Read Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
catch (IOException)
{
MessageBox.Show("Recieve DUT data exception, Serial Port not open", "Read Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
Thread.Sleep(1000);
data_string = "ABORT CODE";
}
return data_string;
}
以前,该程序使用单个类进行所有计算和操作。但是我也担心通过创建一个新类,然后我会通过从我的主类中调用类太多而遇到“Class Envy”。
提前感谢您提供给我的任何帮助。