代码如下所示:
钟:
public class Clock
{
public event Func<DateTime, bool> SecondChange;
public void Run()
{
for (var i = 0; i < 20; i++)
{
Thread.Sleep(1000);
if (SecondChange != null)
{
//how do I get return value for each subscriber?
Console.WriteLine(SecondChange(DateTime.Now));
}
}
}
}
显示时钟:
public class DisplayClock
{
public static bool TimeHasChanged(DateTime now)
{
Console.WriteLine(now.ToShortTimeString() + " Display");
return true;
}
}
日志时钟:
public class LogClock
{
public static bool WriteLogEntry(DateTime now)
{
Console.WriteLine(now.ToShortTimeString() + " Log");
return false;
}
}
运行代码:
var theClock = new Clock();
theClock.SecondChange += DisplayClock.TimeHasChanged;
theClock.SecondChange += LogClock.WriteLogEntry;
theClock.Run();
其他问题是:
- 每个订阅者都返回一个值是一种好习惯吗?
- 将 Action/Func 声明为事件返回类型而不是手动声明委托是一种好习惯吗?