C#里面的委托,说白了就是函数指针

来源:互联网 发布:excel数据无法求和 编辑:程序博客网 时间:2024/04/29 01:11
委托,从字面上,非常让人费解,但实际上,委托就是带类型的函数指针,方便编译器识别、限定和查错。

如果从javascript语言的角度,根本没有这么复杂的概念,比如下面这段:

function a1(name){alert("a1 "+name)}function a2(name){alert("a2 "+name)}var b;b = a1;//把a1赋值给bb("nio")b = a2;//把a2赋值给bb("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);//使用newb1 += new b(a2);//使用newb1("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类型,则限定了委托函数不能被外部的=访问,而只能用+=和-=来访问,避免被=号清空关联的事件链表。





原创粉丝点击