C# 2.类之间通信,其他类调用UI类中的方法

1. 把UI类中的方法通过委托传给f1类,实现f1类调用UI类中的方法(实现例如更新UI、数据处理的功能)
2. 此方法缺点,类与类之间存在过度耦合,后续需开发更好方法
//f1.cs
namespace Prog
{
    
    
    //定义一个数据处理的委托
    public delegate void myDataDelegate(byte[] buf, int length);

    public class f1
    {
    
    
        private myDataDelegate myDataFunc;

        byte[] buf;
        int length;

        public void f1(myDataDelegate delegate1)    //构造函数
        {
    
    
            myDataFunc = delegate1;         //把UI类中的方法通过委托传给f1类
        }
        public void  func() 
        {
    
    
            buf = new byte[100];
            ...
            length = 10;
            myDataFunc(buf, length);        //实现f1类调用UI类中的方法(实现例如更新UI、数据处理的功能)
        }
    }
}

//Form1.cs
namespace Prog
{
    
    
    public partial class Form1 : Form
    {
    
    
        //定义一个数据处理的委托
        myDataDelegate myDataFuncF;

        public Form1()
        {
    
    
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
    
    
            myDataFuncF = new myDataDelegate(DataParseInvoke);
            f1 f1Instance = new f1(myDataFuncF);    //把UI类中的方法通过委托传给f1类
            f1Instance.func();     
        }

        
        private void DataParseInvoke(byte[] buf, int length)
        {
    
    
            //this.Invoke就是跨线程访问ui的方法  以防DataParse()中有UI更新
            Invoke((EventHandler)(delegate
            {
    
    
                DataParse(buf, length);
            })
            );
        }

        private void DataParse(byte[] buf, int length)
        {
    
    
            //串口数据分析
            //UI更新
        }
 
    }
}

Guess you like

Origin blog.csdn.net/lljss1980/article/details/119518923