C# 匿名委托

匿名委托实指匿名方法或 Lambda 表达式。

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour
{
public delegate void A();
public delegate void B(int i);
public delegate void C(int i, float f);

void Start ()
{
//////////////////////// 一般写法 ////////////////////////
A a = AA;
a();
B b = BB;
b(2);
C c = CC;
c(2, 2.0f);

//////////////////////// delegate匿名写法 ////////////////////////
A a1 = delegate()
{
Debug.Log("a1");
};
a1();
B b1 = delegate(int i)
{
Debug.Log("b1 = " + i);
};
b1(2);
C c1 = delegate(int i, float f)
{
Debug.Log("c1 = " + i + ", " + f);
};
c1(2, 2.0f);

//////////////////////// lambda匿名写法 ////////////////////////
A a2 = () =>
{
Debug.Log("a2");
};
a2();
B b2 = (int i) =>
{ // 也可以缩写成 B b2 = i => {}
Debug.Log("b2 = " + i);
};
b2(2);
C c2 = (int i, float f) =>
{ // 也可以缩写成 C c2 = (i, f) => {}
Debug.Log("c2 = " + i + ", " + f);
};
c2(2, 2.0f);
}

private void AA()
{
Debug.Log("AA");
}

private void BB(int i)
{
Debug.Log("BB = " + i);
}

private void CC(int i, float f)
{
Debug.Log("CC = " + i + ", " + f);
}
}