Menu
CoddyTech

委托与闭包

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

C 函数指针只保存函数的地址。它无法捕获局部变量,因此 C 回调通常会接收一个额外的上下文参数,通常是 void * 或结构体指针,用来携带状态。C# 委托(例如 Func<int,int>)是带类型的可调用值,而 lambda 可以直接使用 offset:编译器会将捕获的变量移入一个隐藏对象,并由垃圾回收器确保该对象一直存活。lambda 捕获的是变量本身,而不是副本,因此之后对 offset 的更改也会对它可见。

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

C 参考示例

#include <stdio.h>

struct adder { int offset; };

static int add(const struct adder *self, int value) {
    return value + self->offset;
}

int main(void) {
    struct adder ctx = { 4 };
    int (*fn)(const struct adder *, int) = add;
    printf("%d\n", fn(&ctx, 3));
    return 0;
}

Main 中的 C# 语句

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

这些是用于教学的精简代码片段。挑战文件包含完整的可执行包装代码;上面的片段展示了相关的声明和语句。

参考输出:

7

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自我测试

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

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

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