Menu
CoddyTech

委托与闭包

Coddy 面向 Go 开发者的 C# 课程的第 26 课,共 48 课。

Go 函数值对应于 C# 委托,例如 Func<int,int>。两者都可以捕获外围变量。接受函数的参数是一种行为依赖;调用传入的函数,这样替代实现才能继续有效。

委托表示可调用的值,其参数类型和返回类型都会经过检查。Func<int,int> 接收一个 int 并返回一个 int。Lambda 可以捕获其外层作用域中的变量。使用代码块主体的 Lambda 必须显式返回值;使用表达式主体的 Lambda 会返回其表达式。

Go 参考

package main
import ("fmt")

func main() {
factor:=3;transform:=func(n int)int{return n*factor};fmt.Println(transform(4))
}

Main 中的 C# 语句

int offset = 4;
Func<int,int> add = value => value + offset;
Console.WriteLine(add(3));

这些是重点讲解用的代码片段。挑战文件包含完整、可执行的封装代码;上面的片段展示了相关声明和语句。

参考输出:

12

C# 输出:

7
challenge icon

挑战

简单

返回一个新数组,并将 offset 加到每个值上。定义一个捕获 offset 的 Func<int,int> 回调,并应用它,且不要更改输入。

编辑未锁定的 C# 文件。可见的锁定文件 Main.cs 会读取描述的行,调用 Exercise.Solve,验证输入未被修改,并以一个末尾换行符打印结果。保留已声明的 API。不要添加第二个 Main,也不要打印诊断输出。

亲手试试

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = Ints(input[0]); string before0=Snapshot(a0);
var a1 = I(input[1]); string before1=Snapshot(a1);

var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine("values:" + string.Join(",", result));
}
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Go 开发者的 C#中的所有课

自己练习: C# 在线编译器