源代码
main
#region LambdaClosure
{
Action<string> action = LambdaClosure.MyConsoleWrite();
action("hello!");
action(null);
action(null);
action("world");
action(null);
action(null);
}
#endregion
internal static class LambdaClosure
{
public static Action<string?> MyConsoleWrite()
{
string msg = "";
Action<string?> lambdaClosureAction = (string? info) =>
{
msg = info ?? msg;
Console.WriteLine(msg);
};
return lambdaClosureAction;
}
}
输出结果
解析
public static Action<string?> MyConsoleWrite(){}
本质是一个类,
string msg
是这个类里面的一个成员变量,只是外部无法访问
从而实现了lambda的闭包