在C++下面,指針是一個讓人歡喜讓人憂的東西,其強大無比,個人經驗來看,50%的BUG都是指針的問題,前不久用心看了一下C++下面的函數指針,感覺相當好用,尤其是對於類的封裝而言,其作用類似MFC下面的消息響應,但消息響應似乎只是CWnd下面的東西,如果想將類A調用類B的函數,函數指針是個很正常的選擇。
函數指針,個人而言,多數是當消息響應來用,這個思路可能是由於受Action Script的方法影響,至於好與壞,很難說清楚。在C#下面,由於泛型的存在,指針的概念並不十分明確,但很明顯的,在C#下面實現C++的函數指針功能算挺簡單的,使用的是delegate的方法,你說它是委託也好,說是代理也行。
delegate是C#中的一種類型,它實際上是一個能夠持有對某個方法的引用的類。與其它的類不同,delegate類能夠擁有一個簽名(signature),並且它只能持有與它的簽名相匹配的方法的引用。它所實現的功能與C/C++中的函數指針十分相似。它允許你傳遞一個類A的方法m給另一個類B的對象,使得類B的對象能夠調用這個方法m。但與函數指針相比,delegate有許多函數指針不具備的優點。
下面直接貼代碼好了,比較簡單的例子,看註釋都可以明白的了,純粹是個人備忘用的而已。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Diagnostics; namespace JustTest { //聲明函數指針的類型 public delegate void MsgHandler(string strMsg); //類A public class ClassA { //函數指針 private MsgHandler _msgHandler; //類A的構造函數 public ClassA() { } //設置函數指針的方法 public void SetHandler(MsgHandler h) { this._msgHandler = h; } //在類A內部調用函數指針並傳遞參量 public void DoSomething() { Debug.WriteLine("DoSomething..."); if (this._msgHandler != null) { this._msgHandler("Param"); } } } //使用一個WinForm的應用程序 public partial class Form1 : Form { //定義類A的變量 private ClassA a; public Form1() { InitializeComponent(); //實例化 a = new ClassA(); a.SetHandler(this.ForTest); a.DoSomething(); } //a內部通過函數指針調用的函數 public void ForTest(string s) { Debug.WriteLine("Process in the form , the in string is : " + s); } } }
執行的結果,在VS下的輸出窗體:
DoSomething...
Process in the form , the in string is : Param