c# 委托学习,父子之间传值

本文深入探讨了C#中委托的使用方法,将其比喻为JS或PHP中的闭包,展示了如何将函数作为变量进行调用。通过具体代码示例,详细解释了委托的声明、实例化及调用过程。此外,还介绍了如何实现父子窗口间的值传递,提供了form1和form2间数据交互的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天再次看了委托的教程,有了更深刻的认识。委托就好像js或者php里的闭包一样,把函数当作变量,然后可以调用一样。

写了个代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace weituo
{
    //声明一个委托,委托必须要与被委托的方法保持一致
    public delegate int deleMath(int x,int y);

    public partial class Form5 : Form
    {
        public Form5()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            deleMath s; //委托是一个数据类型,所以我们像变量一样,先定义
            mathOpt ma = new mathOpt(); //实例化对象
            s = ma.Add; //赋值给委托,然后就可以调用了。
            int k = s(2, 3);
            MessageBox.Show(k.ToString());

        }
    }

    public class mathOpt
    {
        public int Add(int x,int y)
        {
            return x+y;
        }

        public int subtract(int x,int y)
        {
            return x-y;
        }
    }
}

然后尝试父子窗口之间的传值

form1的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace weituo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public void chuangzhi(string s)
        {
            textBox1.Text = s;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 frm2 = new Form2(chuangzhi);
            frm2.txtfrm2.Text = textBox1.Text; //传到窗口2
            frm2.ShowDialog();
        }       
        
    }
    
}

form2的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace weituo
{
    //与窗体1的ShowText方法签名相同的委托类型
    public delegate void deleChuanzhi(string s);

    public partial class Form2 : Form
    {
        public deleChuanzhi delecz1;

        public Form2(deleChuanzhi delecz2)
        {
            this.delecz1 = delecz2;
            InitializeComponent();
        }

        private void btnFrm2_Click(object sender, EventArgs e)
        {
            string ss = txtfrm2.Text;
            this.delecz1(ss);
        }
    }

    
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值