我对C#中委托和使用静态变量传参的理解

第一个例子

这是使用static变量进行传参的form1和form2

    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        public void  ShowText(Employee ee)
        {
            richTextBox1.Text=ee.Name+"\r\n"+ee.Post+"\r\n"+ee.Salary+"\r\n";
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Form1 f1 = new Form1();
            richTextBox1.Text = Form1.name + "\r\n" + Form1.post + "\r\n" + Form1.salary;
            f1.ShowDialog();
        }

        private void Form2_Load(object sender, EventArgs e)
        {

        }
    }

    public partial class Form1 : Form
    {
        public static string name;
        public static string post;
        public static string salary;
        //public delegate void MyDelegate(Employee ee);
        //private MyDelegate md;
        public Form1()
        {
            //md = m;
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //cs.Employee ee= new Employee(textBox1.Text, textBox2.Text, textBox3.Text);
            //this.md(ee);
            name = textBox1.Text;
            post = textBox2.Text;
            salary = textBox3.Text;
        }

}

达到的效果是

我对C#中委托和使用静态变量传参的理解

form2中点击按钮打开from1,输入相应的数据后点击按钮后,form2的文本框中没有任何数据,关闭form1,再次点开form2的按钮时才有数据显示

我对C#中委托和使用静态变量传参的理解

这是使用委托

    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        public void  ShowText(Employee ee)
        {
            richTextBox1.Text=ee.Name+"\r\n"+ee.Post+"\r\n"+ee.Salary+"\r\n";
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Form1 f1 = new Form1(ShowText);
            f1.ShowDialog();
        }

        private void Form2_Load(object sender, EventArgs e)
        {

        }
    }

    public partial class Form1 : Form
    {
        public static string name;
        public static string post;
        public static string salary;
        public delegate void MyDelegate(Employee ee);
        private MyDelegate md;
        public Form1(MyDelegate m)
        {
            md = m;
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            cs.Employee ee= new Employee(textBox1.Text, textBox2.Text, textBox3.Text);
            this.md(ee);
        }
    }

我对C#中委托和使用静态变量传参的理解

同样的操作,再form1中点击按钮,数据就会传回form1

 

我对C#中委托和使用静态变量传参的理解

 

第2个例子

使用委托可以很轻易的达到比如换字体的颜色之类的操作,只需再弹出的对话框中点击确定就行,如果使用static进行传参的话,还需要在文本框中再次点击一下

我对C#中委托和使用静态变量传参的理解

不过这并不是委托本身可以传参,委托还是在重载构造函数的基础上进行传递