C#事件的實現


事件是C#中一個重要的內容,MSDN上有一個自定義事件的演示示例。我看了半天有點暈,所以新建了一個winform工程添加了一個按鈕,然後找出調用的程序,一對比做了一個類似的示例,就明白了。看代碼有時候比看文檔來得更快。

所以還是一貫的原則,來乾的,不來稀的。

 

using System;

namespace TestEventArgs
{
	/// <summary>
	/// 這個類對應於EventArgs,做對比學習。
	/// 添加兩個內容:info1,info2。
	/// </summary>
	public class MyEventArgs : EventArgs
	{
		private String info1;
		private UInt32 info2;

		public MyEventArgs(String info1, UInt32 info2)
		{
			this.info1 = info1;
			this.info2 = info2;
		}

		public String Info1
		{
			get { return this.info1; }
			set { this.info1 = value; }
		}

		public UInt32 Info2
		{
			get { return this.info2; }
			set { this.info2 = value; }
		}
	}

	/// <summary>
	/// 仿真Button按鈕
	/// </summary>
	public class MyButton
	{
		public delegate void MyEvnetHandler(object sender, MyEventArgs e);
		/// <summary>
		/// 按鈕點擊的次數計數器
		/// </summary>
		public static UInt32 clicked_num = 0;
		public event MyEvnetHandler MyClick;

		public void 觸發()
		{
			MyEventArgs arg = new MyEventArgs(DateTime.UtcNow.ToString(), ++clicked_num);
			MyClick(this, arg);
		}
	}

	/// <summary>
	/// 仿真Form窗體
	/// </summary>
	public class MyForm
	{
		public MyButton 按鈕;
		public MyForm()
		{
			按鈕 = new MyButton();
			按鈕.MyClick += new MyButton.MyEvnetHandler(this.button_Clicked);
		}


		public void button_Clicked(object sender, MyEventArgs e)
		{
			Console.WriteLine("button clicked(sender is:" + sender.ToString() + "; info1 = "
				+ e.Info1 + "; info2 = " + e.Info2);
		}
	}

	class Program
	{
		static void Main(string[] args)
		{
			MyForm 窗體 = new MyForm();
			for (int i = 0; i < 10; i++ )
			{
				窗體.按鈕.觸發();
				System.Threading.Thread.Sleep(500);
			}
			Console.WriteLine("Press any key to continue...");
			Console.ReadKey();
		}
	}
}


不同的地方:

1 本示例中delegate myevnethandler是mybutton類內部成員,在系統中eventhander是system命名空間下的一個成員。

發佈了76 篇原創文章 · 獲贊 16 · 訪問量 47萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章