C#中利用委托创建窗体单向通信

         初学者在开始学习的时候,对于委托很难做到一下子理解,其中也包括我。委托好比一座大山,没爬上山顶就不能有“一览众山小”的感觉,只有你真正的爬到山顶的时候,才会发现大自然的是神奇。

        委托我们可以把它认为是一个类,而不是一个方法。用委托我们可以调用方法,来简化程序,非常像C++中的指针。

       使用委托的一般步骤为:

      (1)定义委托,delegate 返回值类型 委托类型名称(参数列表);

       (2)声明方法;

       (3)实例化委托,注意声明的类型要和方法中的类型一样。

       下面给出例子,利用委托创建窗体单向通信:

这是主窗体的程序:

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

namespace _561
{
    public partial class Form1 : Form
    {
        public ContactDelegate message;
        public Form1()
        {
            InitializeComponent();

            //从窗体实例化
            FormOther1 form1 = new FormOther1();
            form1.Show();

            //调用委托
            message +=form1.ReceiveDelegate;
        }
        private string word;

        //单击发送按钮
         private void zhudanji_Click(object sender, EventArgs e)
        {
            word = fswbk.Text;
            message(word);
        }
    }
    /// <summary>
    /// 委托定义
    /// </summary>
    public delegate void ContactDelegate(string word);
}

注意委托的定义要在类的外面。

下面给子窗体的程序:

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

namespace _561
{
    public partial class FormOther1 : Form
    {
        public FormOther1()
        {
            InitializeComponent();
        }
        public void ReceiveDelegate(string word)
        {
            this.CCtwbk.Text = word;
        }
    }
}
运行结果:

子窗体和主窗体界面:

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值