码迷,mamicode.com
首页 > Windows程序 > 详细

C# 委托与事件

时间:2016-12-26 21:47:30      阅读:314      评论:0      收藏:0      [点我收藏+]

标签:ati   int   class   his   blog   object   using   turn   handle   

using System;

namespace TheDelegate
{
    public class People
    {
        public static void Say()
        {
            Console.WriteLine("好的,我说一下,是我代干的哈。");
        }
        public static int Sum(int a, int b)
        {
            int c = a + b;
            Console.WriteLine("结果是:{0}", c);
            return c;
        }
        public static int By(int a, int b)
        {
            int c = a * b;
            Console.WriteLine("结果是:{0}", c);
            return c;
        }

        public delegate void SmileEventHandler();
        public event SmileEventHandler OnSmile;
        public void Smile()
        {
            if (OnSmile != null)
            {
                Console.WriteLine("I‘m smiling...");
                OnSmile();
            }
        }
        public delegate void LaougthEventHandler(object sender, EventArgs e);
        public event LaougthEventHandler OnLaougth;
        public void Laougth()
        {
            if (OnLaougth != null)
            {
                Console.WriteLine("I‘m Laougthing, hahahaha...");
                OnLaougth(this, new EventArgs());
            }
        }
    }
    class Program
    {
        public delegate void SayEventHandler();
        public delegate int CalEventHandler(int a, int b);
        static void Main(string[] args)
        {
            SayEventHandler say = new SayEventHandler(People.Say);
            say();
            CalEventHandler cal = new CalEventHandler(People.Sum);
            cal += People.By;
            int res = cal(22, 33);
            Console.WriteLine(res);

            People ppl = new People();
            ppl.OnSmile += new People.SmileEventHandler(ppl_OnSmile);
            ppl.Smile();
            ppl.Smile();
            ppl.OnLaougth += new People.LaougthEventHandler(ppl_OnLaougth);
            ppl.Laougth();
        }
        private static void ppl_OnSmile()
        {
            Console.WriteLine("严肃!");
        }
        private static void ppl_OnLaougth(object sender, EventArgs e)
        {
            Console.WriteLine("安静,安静!\t{0}\t{1}", sender, e);
        }
    }
}

 

C# 委托与事件

标签:ati   int   class   his   blog   object   using   turn   handle   

原文地址:http://www.cnblogs.com/lged/p/6223827.html

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