C#委托-事件示例

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Event_Delegate
{
    class Program
    {
        static void Main(string[] args)
        {
            A a = new A(); //定义首领A
            B b = new B(a);

            a.Raise("左");
            Console.ReadLine();
            //====
            var test = new Heater();
            test.Onboiled += TestOnboiled;
            test.Onboiled += TestOnboiled;
            test.Begin();
            Console.ReadKey();
        }
        static void TestOnboiled(object sender, EventArgs e)
        {
            Console.WriteLine("Hello 事件被调用");

        }
    }

     public delegate void RaiseEventHandler(string hand);

    /// <summary>
    /// 首领A
    /// </summary>
    public class A
    {
        /// <summary>
        /// 首领A举杯事件
        /// </summary>
        public event RaiseEventHandler RaiseEvent;

        public void Raise(string hand)
        {
            Console.WriteLine("首领A举杯");

            //调用举杯事件,传入左或右手作为参数
            if (RaiseEvent != null)
            {
                RaiseEvent(hand);
            }
        }
    }
    /// <summary>
    /// 部下B
    /// </summary>
    public class B
    {
        A a;
        public B(A a)
        {
            this.a = a;
            a.RaiseEvent += new RaiseEventHandler(a_raiseEvent);
        }
        void a_raiseEvent(string hand)
        {
            if (hand.Equals("左"))
            {
                Console.WriteLine("部下B发起攻击 ");
            }
        }
    }
}
Client_1.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Threading;

namespace Event_Delegate
{
    class Client_1
    {
    }

    public class Heater
    {
        public event EventHandler Onboiled;
        private void RasieBoiledEvent()
        {
            if (Onboiled == null)
            {
                Console.WriteLine("加热完成,处理订阅事件为空");
            }
            else
            {
                Onboiled(this,new EventArgs());
            }
        }
        private Thread heatThread;
        public void Begin()
        {
            heatTime = 5;
            heatThread = new Thread(new ThreadStart(Heat));
            heatThread.Start();
            Console.WriteLine("加热器已经开启",heatTime);
        }
        private int heatTime;
        private void Heat()
        {
            while (true)
            {
                Console.WriteLine("加热还需要{0} 秒",heatTime);
                if (heatTime == 0)
                {
                    RasieBoiledEvent();
                    return;
                }
                heatTime--;
                Thread.Sleep(1000);
            }
         }
    }

}

posted on 2019-05-30 10:26  萧橘子  阅读(172)  评论(0编辑  收藏  举报

导航