20150317--委托、代理

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

委托的四大步骤:

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();

创建一个用户控件:

image

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);
        }
    }

新建一个页面

image

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;
    }
原文地址:https://www.cnblogs.com/Tirisfal/p/4344473.html