event作用
我们可以通过对event
的使用完成回调功能。本节通过简单的例子引入Action
和EventHandler
。
EventHandler
class Program
{
private static event EventHandler<DiagnosticsArgs> DiagnosticsEvent;
static void Main(string[] args)
{
DiagnosticsEvent += Program_DiagnosticsEvent;//注册回调函数
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
DiagnosticsEvent?.Invoke(null, new DiagnosticsArgs(100, false));//唤醒回调函数Program_DiagnosticsEvent
}
Thread.Sleep(500);
}
}
/// <summary>
/// 回调函数本身
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void Program_DiagnosticsEvent(object sender, DiagnosticsArgs e)
{
Console.WriteLine(e.FirstParamater + "\n" + e.SecondParameter);
}
}
internal class DiagnosticsArgs : EventArgs
{
private int _firstParamater;
public int FirstParamater
{
get { return _firstParamater; }
set { _firstParamater = value; }
}
private bool _secondParameter;
public bool SecondParameter
{
get { return _secondParameter; }
set { _secondParameter = value; }
}
public DiagnosticsArgs(int first, bool second)
{
FirstParamater = first;
SecondParameter = second;
}
}
结果:
Action
class Program
{
//private static event EventHandler<DiagnosticsArgs> DiagnosticsEvent;
private static event Action<DiagnosticsArgs> DiagnosticsEvent;
static void Main(string[] args)
{
DiagnosticsEvent += Program_DiagnosticsEvent;//注册回调函数
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
//DiagnosticsEvent?.Invoke(null, new DiagnosticsArgs(100, false));//唤醒回调函数Program_DiagnosticsEvent
DiagnosticsEvent?.Invoke(new DiagnosticsArgs(100, false));//唤醒回调函数Program_DiagnosticsEvent
}
Thread.Sleep(500);
}
}
private static void Program_DiagnosticsEvent(DiagnosticsArgs e)
{
Console.WriteLine(e.FirstParamater + "\n" + e.SecondParameter);
}
/// <summary>
/// 回调函数本身
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
//private static void Program_DiagnosticsEvent(object sender, DiagnosticsArgs e)
//{
// Console.WriteLine(e.FirstParamater + "\n" + e.SecondParameter);
//}
}
internal class DiagnosticsArgs : EventArgs
{
private int _firstParamater;
public int FirstParamater
{
get { return _firstParamater; }
set { _firstParamater = value; }
}
private bool _secondParameter;
public bool SecondParameter
{
get { return _secondParameter; }
set { _secondParameter = value; }
}
public DiagnosticsArgs(int first, bool second)
{
FirstParamater = first;
SecondParameter = second;
}
}
运行结果和上一次相同。
结论
单从功能上来讲,二者都可以实现函数回调,但是从设计模式的角度来看,EventHandler
的封装性似乎更好,具体可参考StackOverflow相关讨论。