zoukankan      html  css  js  c++  java
  • 关于C#的委托与事件的一个小DEMO

    从学习.NET到现在,也有快4年时间了,一切都是在不经意间忽略,写了几年的代码,委托与事件其实一直在用,可以真的有人让我为一个类写一个事件,我真的会犹豫一下要如何写。

    以下是我写的一个小DEMO。

    设定一个闹钟。

    namespace ConsoleApplication6
    {
        public delegate void BellEventHandler(object sender, BellEventArgs e);
        public class BellEventArgs : EventArgs
        {
            public readonly int h;
            public readonly int m;
            public readonly int s;
            public BellEventArgs(int h, int m, int s)
            {
                this.h = h;
                this.m = m;
                this.s = s;
            }
        }
        
        class Program
        {
            static void Main(string[] args)
            {
                NaoZhong t = new NaoZhong();
                t.SetBellTime(13400);
                t.Bell += new BellEventHandler(t_Bell);
                t.StartBell();
            }
            static void t_Bell(object sender, BellEventArgs e)
            {
                Console.Write("{0}:{1}:{2}了,懒猪起床了", e.h.ToString(), e.m.ToString(), e.s.ToString());
                Console.Read();
            }

        }
        public class NaoZhong
        {
            private int Hours = 0;
            private int Minutes = 0;
            private int Seconds = 0;

            public event BellEventHandler Bell;

            public void StartBell()
            {
                while (!(DateTime.Now.Hour == Hours && DateTime.Now.Minute == Minutes && DateTime.Now.Second == Seconds))
                {


                }
                BellEventArgs e = new BellEventArgs(Hours, Minutes, Seconds);
                Bell(this, e);
            }
            public bool SetBellTime(int _h, int _m, int _s)
            {
                if (_h > 24)
                {
                    return false;
                }
                if (_m > 60)
                {
                    return false;
                }
                if (_s > 60)
                {
                    return false;
                }
                Hours = _h;
                Minutes = _m;
                Seconds = _s;
                return true;
            }

        }

    }

     学习委托与事件

  • 相关阅读:
    Reface.AppStarter 基本示例
    Reface.AppStarter 类型扫描 —— 获得项目中所有的实体类型
    多线程和异步有什么关联和区别?如何实现异步?
    事件总线功能库,Reface.EventBus 详细使用教程
    代理模式是什么?如何在 C# 中实现代理模式
    监听者模式在系统中的应用 —— 事件总线
    如何将 .NetFramework WebApi 按业务拆分成多个模块
    Reface.NPI 方法名称解析规则详解
    EF 太重,MyBatis 太轻,ORM 框架到底怎么选 ?
    Reface.AppStarter 框架初探
  • 原文地址:https://www.cnblogs.com/guolihao/p/2609944.html
Copyright © 2011-2022 走看看