我试图在名为Modbus的类中为SerialPort.DataReceived设置自己的事件,我有一个Windows Form应用程序,希望在接收到数据时触发此事件。这是代码:
FROM oracle AS needs-squashing
ENV NEEDED_VAR some_value
COPY ./giant.zip ./somewhere/giant.zip
RUN echo "install giant in zip"
RUN rm ./somewhere/giant.zip
FROM scratch
COPY --from=needs-squashing / /
ENV NEEDED_VAR some_value
错误在public class Modbus
{
public delegate void SerialDataReceivedEventHandler(object sender, SerialDataReceivedEventArgs e);
public event SerialDataReceivedEventHandler DataReceived;
static SerialPort modbusPort;
public Modbus(int baudRate, string port)
{
modbusPort = new SerialPort();
modbusPort.BaudRate = baudRate;
modbusPort.PortName = port;
modbusPort.Open();
modbusPort.DataReceived += Incoming;
}
private void Incoming (object sender, SerialDataReceivedEventArgs e)
{
if (DataReceived != null)
{
SerialDataReceivedEventArgs rea = new SerialDataReceivedEventArgs { Data = e.Data };
DataReceived(this, rea);
}
}
}
public class SerialDataReceivedEventArgs : EventArgs
{
public string Data { get; set; }
}
行
答案 0 :(得分:0)
要么Incoming
是static
(因为modbusPort
被声明为static
),要么从static
声明中删除modbusPort
。我认为后者在这里更合适(在非静态构造函数中实例化static
引用可能是一种气味)。
我认为您的代码应如下所示:
public class Modbus
{
public delegate void SerialDataReceivedEventHandler(object sender, SerialDataReceivedEventArgs e);
public event SerialDataReceivedEventHandler DataReceived;
private readonly SerialPort modbusPort; // CHANGED THIS LINE
public Modbus(int baudRate, string port)
{
modbusPort = new SerialPort();
modbusPort.BaudRate = baudRate;
modbusPort.PortName = port;
modbusPort.Open();
modbusPort.DataReceived += Incoming;
}
private void Incoming (object sender, SerialDataReceivedEventArgs e)
{
if (DataReceived != null)
{
SerialDataReceivedEventArgs rea = new SerialDataReceivedEventArgs { Data = e.Data };
DataReceived(this, rea);
}
}
}
答案 1 :(得分:0)
所以几个小时后我找到了解决方案,我发布了最终代码:
这是我班上的代码
public class Modbus
{
public delegate void SerialDataReceivedEventHandler(object sender, SerialDataReceivedEventArgs args);
public event SerialDataReceivedEventHandler DataReceived;
private readonly SerialPort modbusPort;
public Modbus(int baudRate, string port)
{
modbusPort = new SerialPort();
modbusPort.BaudRate = baudRate;
modbusPort.PortName = port;
modbusPort.Open();
modbusPort.DataReceived += Incoming;
}
private void Incoming(object sender, SerialDataReceivedEventArgs args)
{
DataReceived?.Invoke(this, args);
}
public byte[] readE()
{
int size = modbusPort.ReadBufferSize;
byte[] buffer = new byte[size];
modbusPort.Read(buffer, 0, 1);
return buffer;
}
}
代码int Windows窗体,下一行是我初始化Modbus对象
myModbus.DataReceived += Incoming;
和定义
private void Incoming(object sender, SerialDataReceivedEventArgs e)
{
Byte[] indata = myModbus.readE();
}