C#裏面的委託,說白了就是函數指針

委託,從字面上,非常讓人費解,但實際上,委託就是帶類型的函數指針,方便編譯器識別、限定和查錯。

如果從javascript語言的角度,根本沒有這麼複雜的概念,比如下面這段:

function a1(name){
	alert("a1 "+name)
}
function a2(name){
	alert("a2 "+name)
}
var b;
b = a1;		//把a1賦值給b
b("nio")
b = a2;		//把a2賦值給b
b("nio")        

而用C#來寫,就比較囉嗦了,忍不住吐槽一下。

using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
	public delegate void b(string name);
	void Start () {
		b b1 = a1;
		b b2 = a2;
		b1("nio");
		b2("nio");
	}
	private static void a2(string name) {
		Debug.Log("a2 "+name);
	}
	private static void a1(string name) {
		Debug.Log("a1 "+name);
	}
}

或者換一下寫法:

using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {
	public delegate void b(string name);
	public b b1;
	void Start () {
		b1 += a1;
		b1 += a2;//這裏用了加等的方法,這樣b1裏面就包含了兩個函數,a1和a2,(也可以用減等來去掉函數)
		b1("nio");
	}
	private static void a2(string name) {
		Debug.Log("a2 "+name);
	}
	private static void a1(string name) {
		Debug.Log("a1 "+name);
	}
}
使用new的寫法:
using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {
	public delegate void b(string name);
	public b b1;
	void Start () {
		b1 += new b(a1);//使用new
		b1 += new b(a2);//使用new
		b1("nio");
	}
	private static void a2(string name) {
		Debug.Log("a2 "+name);
	}
	private static void a1(string name) {
		Debug.Log("a1 "+name);
	}
}

又或者:

using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {
	public delegate void b(string name);
	public b b1;
	void Start () {
		b1 = new b();
		b1 += a1;
		b1 += a2;
		b1("nio");
	}
	private static void a2(string name) {
		Debug.Log("a2 "+name);
	}
	private static void a1(string name) {
		Debug.Log("a1 "+name);
	}
}

而Action則是委託的簡寫(在函數不需要返回值的時候可以使用Action):

using System;
using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {
	public Action<string> b1;
	void Start () {
		b1 += a1;
		b1 += a2;
		b1("nio");
	}
	private static void a2(string name) {
		Debug.Log("a2 "+name);
	}
	private static void a1(string name) {
		Debug.Log("a1 "+name);
	}
}

至於eventl類型,則限定了委託函數不能被外部的=訪問,而只能用+=和-=來訪問,避免被=號清空關聯的事件鏈表。





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章