c#委托

委托:是一种引用方法的类型。

特点:

1、委托类似于 C++ 函数指针,但它是类型安全的。

2、委托允许将方法作为参数进行传递。

3、委托可用于定义回调方法。

4、委托可以链接在一起;例如,可以对一个事件调用多个方法。

5、方法不需要与委托签名精确匹配。

实例:热水器给水加热,到水温超过95读时,做两件事,1、发出警报CallTempletrue,2、显示温度ShowTempletrue;

    class Heater
    {
        private int templetrue;
        public delegate void Boilhandler(int temple);
        public event Boilhandler BoilEvent;

        //烧水
        public void BoilWater()
        {
            for (int i = 0; i <= 100; i++)
            {
                templetrue = i;

                if (templetrue > 95)
                {
                    if (BoilEvent != null)
                    {//当注册的委托存在时
                        BoilEvent(templetrue);
                    }
                }
            }
        }
    }

    class CallTempletrue
    {
        public void Call(int temple)
        {
           Console.WriteLine("Call:滴滴滴滴!实时温度{0}", temple);
        }
    }
    class ShowTempletrue
    {
        public static void Show(int temple)
        {
            if (temple < 100)
            {
                Console.WriteLine("Show:现在水温{0}!水快开啦!!", temple);
            }
            else
            {
                Console.WriteLine("Show:现在水温{0}!水已经开啦!!", temple);
            }
        }
    }

C#事件,也是一种特殊的委托

posted @ 2013-07-23 15:24  loklook123  阅读(144)  评论(0编辑  收藏  举报