Home
12 匿名函数
Unity
12 匿名函数
姜睿
姜睿
September 07, 2022
1 min

Table Of Contents

01
语法
02
注意事项
03
Lambda 表达式

语法

  • 方法只使用 1 次,没有必要建立独立的具名方法。
  • 匿名方法:实例化委托时 内联声明 的方法。
1
2using static System.Console;
3
4internal class Program
5{
6delegate void Delegate();
7
8static void Method()
9{
10WriteLine("@Method");
11}
12
13private static void Main()
14{
15Delegate d = Method;
16d(); // "@Method"
17}
18}
19
1
2// delegate (params) { // code block };
3
4using static System.Console;
5
6internal class Program
7{
8delegate void Delegate();
9private static void Main()
10{
11Delegate d = delegate ()
12{
13WriteLine("@Method");
14};
15
16d(); // "@Method"
17}
18}
19

注意事项

省略 params 关键字

  • 匿名方法的参数列表必须省略 params 关键字。
1
2using static System.Console;
3internal class Program
4{
5delegate void Delegate(params int[] i);
6private static void Main()
7{
8Delegate d = delegate (int[] i)
9{
10foreach (int num in i)
11{ Write(num + " "); }
12};
13
14d(1, 2, 3); // 1 2 3
15}
16}
17

参数匹配

  • CS19531: Delegate ‘del’ does not take ‘number’ arguments.
1
2using static System.Console;
3internal class Program
4{
5delegate void Delegate();
6private static void Main()
7{
8// CS1593
9Delegate d = delegate (int i)
10{
11WriteLine("@Method");
12};
13
14d(); // "@Method"
15}
16}
17

返回值匹配

  • CS8030: Cannot convert lambda expression to ‘type’ because it is not a delegate type.
1
2using static System.Console;
3internal class Program
4{
5delegate void Delegate();
6private static void Main()
7{
8Delegate d = delegate ()
9{
10WriteLine("@Method");
11// CS8030
12return 1;
13};
14
15d(); // "@Method"
16}
17}
18

Lambda 表达式

1
2using static System.Console;
3internal class Program
4{
5delegate int Delegate(int x, int y = 0);
6private static void Main()
7{
8// classic
9Delegate d = delegate (int x, int y)
10{ return x + y; };
11WriteLine(d(1, 1)); // 2
12
13// lambda expression #1
14d = (int x, int y) =>
15{ return x + y; };
16WriteLine(d(1, 1)); // 2
17
18// lambda expression #2
19d = (x, y) =>
20{ return x + y; };
21WriteLine(d(1, 1)); // 2
22
23// lambda expression #3
24d = (x, y) => x + y;
25// Console.WriteLine(x);
26WriteLine(d(1, 1)); // 2
27}
28}
29

  1. Compiler Error CS1953 | Microsoft Docs

Tags

#game develop
姜睿

姜睿

学生

游戏设计学生

Expertise

游戏开发
平面设计

Related Posts

策略模式
策略模式
November 19, 2023
1 min

Legal Stuff

Privacy NoticeCookie PolicyTerms Of Use