我在C#串口开发中,碰到一个问题。
各个Class类都需要操作同一个硬件串口,发送CMD数据。
我首先用的是委托,但Class变多后,委托呼来呼去,自己都看不懂自己写的程序了。
想怎么解决这个问题。
解决如下:类内静态
这样在其他类内只要new出Help_SerialPort类。就不用关心串口已打开的问题。因为虽然这个类是消失了,但里面的串口是static的,串口仍然不消失。你在其他类内再new出Help_SerialPort类,串口还是上次的串口;
Help_SerialPort类
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace serialportx.help_class
{
public class Help_SerialPort
{
public static SerialPort SerialPort1 =new SerialPort ("COM3",9600);//类内静态,类消失,类内对象不消失
public Help_SerialPort( )//初始化构造方法
{
}
public void open_打开串口()
{
SerialPort1.Open();
}
public void close_关闭串口()
{
SerialPort1.Close();
}
public void TX_发送数据(string data)
{
byte[] buffer= Encoding.Default.GetBytes(data);
SerialPort1.Write(buffer,0,buffer.Length );
}
}
}
Class1类: 用于打开串口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace serialportx.help_class
{
internal class Class1
{
Help_SerialPort x=new Help_SerialPort();
public void open()
{
x.open_打开串口();
}
}
}
Class2: 用于串口发送
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using serialportx;
namespace serialportx.help_class
{
internal class Class2
{
Help_SerialPort x=new Help_SerialPort();
public void send(string data)
{
x.TX_发送数据(data);
}
}
}
这样Class3或其他类都是这么操作,这就解决了串口发送问题了。你再建个modbus协议的库,这个库肯定要控制串口发送数据,用这种办法就解决各个CLASS库调用串口的问题了。
UI主程序
using serialportx.help_class;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace serialportx
{
public partial class Form1 : Form
{
Class1 c1 = new Class1();//class1用于打开串口
Class2 c2 = new Class2();//class2用于串口发送
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
c1.open();
}
catch (Exception)
{
button1.BackColor = Color.Red;
//throw;
}
}
private void button2_Click(object sender, EventArgs e)
{
c2.send(textBox1.Text);
}
}
}
2个按钮操作2个类,控制同一个硬件串口。
在后期:可以用多态的方法。
多态的原理: 多态是利用继承,每个子类都有共同的父类类型。利用new出父类类型集合,集中管理派生出来的子类。可以取出子类内的对象。