委托与事件

委托是C#中最为常见的内容。与类、枚举、结构、接口一样,委托也是一种类型。类是对象的抽象,而委托则可以看成是函数的抽象。一个委托代表了具有相同参数列表和返回值的所有函数。先上一段代码:
public class ClassA
{
    public delegate int CalculationDelegate(int x, int y);//定义一个委托,关键字delegate
    public int Add(int x, int y)//定义一个和委托类型相同的方法
    {
        return x + y;
    }
    public int Sub(int x, int y)//定义一个和委托类型相同的方法
    {
        return x - y;
    }
    public ClassA() {
        CalculationDelegate c = Add;//实例化一个委托,并将方法赋给该委托
        int z = CalculationNum(c,1,2);//将实例化后的委托当作参数传给计算方法
    }
    public int CalculationNum(CalculationDelegate c,int x,int y)
    {
        return c(x,y);//由于传进来的方法为add,所以结果是3。类似与“模板方法模式”
    }
}

 事件是一种特殊的委托,委托一般用于回调,而事件用于外部接口。不多说,先上代码:

public class BaseEventCat
{
    private string name;
    public BaseEventCat(string name)
    {
        this.name = name;
    }
    public delegate void CatShoutEventHandler();//声明委托
    public event CatShoutEventHandler CatShout;//声明事件,事件类型是委托CatShoutEventHandler
    public void Shout()
    {
        MessageBox.Show("喵喵喵,我是"+name,name);
        //如果事件被实例化了就执行猫叫事件
        if (CatShout != null)
        {
            CatShout();
        }
    }
}
public class BaseEventMouse
{
    private string name;
    public BaseEventMouse(string name)
    {
        this.name = name;
    }
    public void Run()
    {
        MessageBox.Show("跑呀",name);
    }
}
private void Button1_Click(object sender, EventArgs e)
{
    BaseEventCat cat = new BaseEventCat("Tom");
    BaseEventMouse mouse1 = new BaseEventMouse("Jack");
    BaseEventMouse mouse2 = new BaseEventMouse("Reber");

    cat.CatShout += new BaseEventCat.CatShoutEventHandler(mouse1.Run);
    cat.CatShout += new BaseEventCat.CatShoutEventHandler(mouse2.Run);

    cat.Shout();
}
 
posted @ 2020-01-16 17:14  梁仕博  阅读(112)  评论(0)    收藏  举报