PowerShell:一种创建闭包的优雅方式 [英] PowerShell: an elegant way to create closures

查看:396
本文介绍了PowerShell:一种创建闭包的优雅方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Keith Hill 向我解释说,块不是闭包,并从块创建闭包我必须调用方法。GetNewClosure()

Keith Hill explained me that blocks in PowerShell are not closures and that to create closures from blocks I have to call method .GetNewClosure().

从块创建闭包? (例如创建包装函数,别名?,...)

Is there any elegant way to create closures from blocks? (e.g. create a wrapping function, an alias?, ...)

示例:

{ block }
${ closure } # ???


推荐答案

您可以创建一个函数, GetNewClosure并返回闭包。必须使用点运算符调用此函数,例如:

You could create a function that takes a scriptblock, calls GetNewClosure and returns the closure. It is essential that you call this function using the dot operator e.g.:

function =>([scriptblock]$_sb_)
{
    $_sb_.GetNewClosure()
}

function A($block) 
{
    B (. => {Write-Host 2; &$block})
}

function B($block) {Write-Host 1;&$block}

A {Write-Host 3}

不确定这比在脚本块上调用GetNewClosure 。注意,你可以选择一些其他名称的功能。我正在寻找更像C#lambdas的东西。

Not sure this is much better than just calling GetNewClosure() on the scriptblock though. Note you can pick some other name for the function. I was going for something more like C# lambdas.

这篇关于PowerShell:一种创建闭包的优雅方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆