直接看代碼:
using System;
namespace ConsoleApp6
{
class Program
{
static void Main(string[] args)
{
Counter c = new Counter(new Random().Next(10));
c.ThresholdReached += c_ThresholdReached;
c.ThresholdReached?.Invoke(null,null);//這裏報錯是類的事件觸發只能在Counter類的內部,外部只能進行綁定或者解綁
Console.WriteLine("press 'a' key to increase total");
while (Console.ReadKey(true).KeyChar == 'a')
{
Console.WriteLine("adding one");
c.Add(1);
}
}
static void c_ThresholdReached(object sender, ThresholdReachedEventArgs e)
{
Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached);
Environment.Exit(0);
}
}
class Counter
{
private int threshold;
private int total;
public Counter(int passedThreshold)
{
threshold = passedThreshold;
}
public void Add(int x)
{
total += x;
ThresholdReached(null, null);//定義事件的類的內部不僅可以直接執行事件也可以進行事件的綁定與解綁操作
ThresholdReached += c_ThresholdReached;
if (total >= threshold)
{
ThresholdReachedEventArgs args = new ThresholdReachedEventArgs();
args.Threshold = threshold;
args.TimeReached = DateTime.Now;
OnThresholdReached(args);
}
}
protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)//觸發事件的方法
{
ThresholdReached?.Invoke(this, e);
}
static void c_ThresholdReached(object sender, ThresholdReachedEventArgs e)
{
Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached);
Environment.Exit(0);
}
public event EventHandler<ThresholdReachedEventArgs> ThresholdReached;//定義事件
}
public class ThresholdReachedEventArgs : EventArgs
{
public int Threshold { get; set; }
public DateTime TimeReached { get; set; }
}
//學習記錄:
//1 .net提供了現成的委託類型EventHandler及EventHandler<TEventArgs>,我們可以直接拿來定義事件,如果定義的事件沒有事件數據,則使用EventHandler,
//否則使用EventHandler<TEventArgs>,注意EventHandler並不是沒有EventArgs,而是使用EventArgs基類本身而進行了省略.需要說明的是這兩個委託類型
//都不帶有返回值,如果需要定義帶有返回值的委託類型需要自行定義。
//2.關於EventArgs:表示包含事件數據的類的基類,並提供要用於不包含事件數據的事件的值。包含數據數據時從EventArgs繼承並定義自己的業務數據,
//如上ThresholdReachedEventArgs
//3.類定義的事件儘管由public修飾,但類內部及外部的對事件的訪問權限是不一樣的,外部只能進行綁定(+=)或解綁(-=)操作,
//內部不僅可以直接執行事件也可以進行事件的綁定與解綁操作,
//因此通常會在類的內部再封裝一個方法(儘管可以不封裝)來觸發事件,同時處理一些穩定的業務邏輯.
}