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

C#方法回调

时间:2019-03-08 23:47:01      阅读:277      评论:0      收藏:0      [点我收藏+]

标签:oda   interface   call   cal   cap   cut   day   eve   time()   

通过接口

    class Program
    {
        static void Main1(string[] args)
        {
            var controller = new Controller(new CallBack());
            controller.Execute();
        }
    }

    public interface ICallBack
    {
        void Run();
    }
    public class CallBack : ICallBack
    {
        public void Run()
        {
            Console.WriteLine(DateTime.Now);
        }
    }
    public class Controller
    {
        private ICallBack _callBack;
        public Controller(ICallBack callBack)
        {
            this._callBack = callBack;
        }
        public void Execute()
        {
            Console.WriteLine("点击任何键返回当前时间,ESC退出");
            while (Console.ReadKey(true).Key != ConsoleKey.Escape)
            {
                _callBack.Run();
            }
        }
    }

通过委托

    public class DelegateCallback
    {
        static void Main(string[] args)
        {
            var controller = new Controller(new Action(() => Console.WriteLine(DateTime.Now)));
            //controller.AddEvent(() => Console.WriteLine(DateTime.Today));
            controller.Execute();
        }
    }
    public class Controller
    {
        private Action _showTime;
        public Controller(Action showTime)
        {
            this._showTime += showTime;
        }
        public void AddEvent(Action act)
        {
            this._showTime += act;
        }
        public void Execute()
        {
            Console.WriteLine("点击任何键返回当前时间,ESC退出");
            while (Console.ReadKey(true).Key != ConsoleKey.Escape)
            {
                _showTime();
            }
        }
    }

定时回调

    public class TimeCallback
    {
        static void Main(string[] args)
        {
            var ti = new TaskInfo();
            var tm = new Timer(state =>
            {
                TaskInfo info = state as TaskInfo;
                info.count++;
                Console.WriteLine(info.count);
            }, ti, 0, 1000);
            Console.ReadKey();
        }
    }
    public class TaskInfo
    {
        public int count = 0;
    }

C#方法回调

标签:oda   interface   call   cal   cap   cut   day   eve   time()   

原文地址:https://www.cnblogs.com/yinchh/p/10498753.html

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