委托与事件

来源:互联网 发布:电影剧照 知乎 编辑:程序博客网 时间:2024/06/05 08:04

好长时间一直弄不明白事件到底是怎么一回事,是怎么触发的,以及怎么订阅的,怎么调用订阅后的方法,今天偶然间看了看一些例子程序,原来挺简单的,我怎么就钻到牛角尖里去了呢,无语...

 

    //委托类
    class DeleteEvent
    {
        //定义string类型的委托
        public delegate string Cat();

        //定义两个事件
        public event Cat eventOne;
        public event Cat eventTow;

        //调用事件
        public string CatShout()
        {
            string cat = "";
            cat = eventOne() + "/r/n" + eventTow();
            return cat;
        }

        public string Shout()
        {
            string cat = "猫叫了一声:喵...";
            return cat;
        }
    }

 

 

    //主人类
    public class Host
    {
        //主人的反应
        public string HostAction()
        {
            string h="主人惊醒...";
            return h;
        }
    }

 

 

    //老鼠类
    public class Moust
    {
        //老鼠的反应
        public string MoustAction()
        {
            string m = "老鼠吓跑了......";
            return m;
        }
    }

 

 

 

    //客户端

    class Program
    {
        private DeleteEvent objDegate = new DeleteEvent();
        private Host objHost = new Host();
        private Moust objMoust = new Moust();
       
        static void Main(string[] args)
        {
            Program test = new Program();
            test.Transfer();

        }

        //客户端调用
        void Transfer()
        {
            //将老鼠与主人的动作加入委托
            objDegate.eventOne += new DeleteEvent.Cat(objHost.HostAction);
            objDegate.eventTow += new DeleteEvent.Cat(objMoust.MoustAction);

            Console.WriteLine(objDegate.Shout());
            //执行
            Console.WriteLine(objDegate.CatShout());
            Console.Read();
        }
    }

 

 

 

原创粉丝点击