A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 孟庆波 中级黑马   /  2012-4-19 17:02  /  1041 人查看  /  0 人回复  /   1 人收藏 转载请遵从CC协议 禁止商业使用本文

1. 类b 去委托类a去做某件事情
2.类b中声明委托,定义事件
3.在类a 中+=将类b与类a关联起来

实例:
首先建立
Form1 ,Form2窗体
Form2窗体通过事件调用Form1窗体的方法,获得值,传值等

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 委托2
{
    public partial class Form2 : Form
    {
    //声明带参数的委托
        public delegate string strDelegate(string words);
   //定义事件
        public event strDelegate strEvent;
        public Form2()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            if (showEvent != null)
            {
                //textBox1.text为委托的参数
                //接受从form1中的参数
                this.textBox2.Text = showEvent(this.textBox1.Text);
            }
        }


    }
}

2.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 委托2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
         //Form2 的委托与Form1建立连接
           Form2 f2 = new Form2();
            f2.showEvent += new Form2.showdelegate(f2_showEvent);
            f2.Show();
        }
        public string CountTime()
        {
            DateTime dt = DateTime.Now;
            return dt.Second.ToString();
        }
        string f2_showEvent(string words)
        {
            //words 为from2传来的参数
            this.textBox1.Text = words;
            //调用form1的方法CountTime()
            return "abc" + CountTime();

        }
    }
}

评分

参与人数 1技术分 +2 收起 理由
宋天琪 + 2

查看全部评分

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马