委托,事件 烧水的小dmeo

烧水的类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// 订阅事件,通过烧水的温度,到一定温度的时候,触发事件
/// </summary>
namespace Boilwater
{
    class boilwater
    {
        public delegate void testDelegate(int temperature);
        public event testDelegate testevent;
        public int temperature=30;

        public void boil()
        {
            while(temperature<=100)
            {
                temperature++;
                Thread.Sleep(1000);
                if (testevent != null)
                {
                    testevent(temperature);
                }
            }
        }
        public static void Alarm1(int temperature)
        {
            Console.WriteLine("当前水温"+temperature+"度");
        }
        public static void Alarm2(int temperature)
        {
            Console.WriteLine("快要烧开了");
        }
        
    }
}

main

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

namespace Boilwater
{
    class Program
    {
        static void Main(string[] args)
        {
            boilwater b = new boilwater();
            b.testevent += boilwater.Alarm1;
            b.testevent += boilwater.Alarm2;
            b.boil();
            Console.ReadKey();
        }
    }
}
发布了89 篇原创文章 · 获赞 4 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/m0_37879526/article/details/104526078
今日推荐