C#方法回调
2021-06-12 19:06
标签:oda interface call cal cap cut day eve time() C#方法回调 标签:oda interface call cal cap cut day eve time() 原文地址:https://www.cnblogs.com/yinchh/p/10498753.html通过接口
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;
}