码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2016-05-07 07:11:20      阅读:268      评论:0      收藏:0      [点我收藏+]

标签:

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

        委托我们可以把它认为是一个类,而不是一个方法。用委托我们可以调用方法,来简化程序,非常像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;
        }
    }
}
运行结果:
技术分享

子窗体和主窗体界面:技术分享技术分享

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

标签:

原文地址:http://blog.csdn.net/j_kang/article/details/51330199

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!