串口访问的委托问题?
第一步 定义了一个串口基类
/// <summary>
/// 串口基类
/// </summary>
public abstract class HardwareBase
{
public delegate void DataReceivedHander(object sender, SerialDataReceivedEventArgs e);
public event DataReceivedHander DataReceived;
/// <summary>
/// 发送命令
/// </summary>
/// <param name="text"></param>
public abstract void Write(string text);
/// <summary>
/// 读串口数据
/// </summary>
/// <returns></returns>
public abstract byte[] Read();
/// <summary>
/// 打开串口
/// </summary>
public abstract void Open();
}
第二 写了个串口类
public class SerialPortEx:HardwareBase
{
SerialPort serial = null;
/// <summary>
/// 构造初始化串口
/// </summary>
/// <param name="portName"></param>
/// <param name="baudRate"></param>
/// <param name="parity"></param>
/// <param name="dataBits"></param>
/// <param name="stopBits"></param>
public SerialPortEx(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
{
serial = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
}
/// <summary>
/// 写串口数据
/// </summary>
/// <param name="text"></param>
public override void Write(string text)
{
try
{
serial.Write(text);
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 读取串口数据
/// </summary>
/// <returns></returns>
public override byte[] Read()
{
byte[] receivedBuffer = new byte[serial.BytesToRead];
serial.Read(receivedBuffer, 0, receivedBuffer.Length);
return receivedBuffer;
}
/// <summary>
/// 打开串口
/// </summary>
public override void Open()
{
try
{
serial.Open();
serial.DataReceived += new SerialDataReceivedEventHandler(serial_DataReceived);
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 串口返回数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public override void serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//base.DataReceived(sender, e);
}
第三步:
serial = new SerialPortEx(portName, baudRate, parity, dataBits, stopBits);
serial.Open();
serial.DataReceived += new HardwareBase.DataReceivedHander(serial_DataReceived);
???这里如何通过一个委托事件通知HardwareBase.DataReceivedHander 接收数据?
哪位给指点一下。万分感激
[解决办法]
serial.DataReceived += new HardwareBase.DataReceivedHander(serial_DataReceived);
这一句 你已经给 serial.DataReceived 这个委托绑定了方法 那么你就调用serial.DataReceived(数据);
[解决办法]
我是想在第二步的SerialPortEx类里面接收到了串口的数据后 主动通知他的上级去做收数据的处理