码迷,mamicode.com
首页 > 其他好文 > 详细

20150317--委托、代理

时间:2015-03-17 15:33:32      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

指向方法的指针。
代理与它指向的方法,往往不是一个人写出来的。

委托的四大步骤:

1.声明代理类型

    public delegate void xyDelegate(string r);

2.定义代理变量

    public event xyDelegate xy;//event

3.将代理挂载到相应的方法上

      Search1.Show += ShowLable;

4.编写代理调用的方法

    if (Show != null)
    {
         Show(s);
    }

代理与类、接口是同一个层次的。
代理与类思想上完全一样。

//定义类的类型
public class Ren
{
    string Name;
    int Age;
    public void Speak()
    {
        ....
    }
}
//定义类型的变量
private Ren r;
//实例化对象
r = new Ren();
//调用对象。
r.Speak();

 

创建一个用户控件:

技术分享

cs中代码:

public delegate void xyDelegate(string s);//声明代理类型
    public event xyDelegate Show;//定义代理变量
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btn_Click(object sender, EventArgs e)
    {
        //执行查询。。。。。
        string s = DateTime.Now.ToString();
        //显示。
        if (Show != null)
        {
            Show(s);
        }
    }

新建一个页面

技术分享

protected void Page_Load(object sender, EventArgs e)
    {
        Search1.Show += ShowLable;
        Search1.Show += Search1_Show;
    }

    void Search1_Show(string s)
    {
    }
    private void ShowLable(string txt)
    {
        Label1.Text = txt;
    }

20150317--委托、代理

标签:

原文地址:http://www.cnblogs.com/Tirisfal/p/4344473.html

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