PowerShell: an elegant way to create closures

百般思念 提交于 2019-12-04 21:22:07

问题


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?, ...)

Example:

{ block }
${ closure } # ???

回答1:


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}

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.




回答2:


These links might be of some help they talk about closures in PowerShell 2.0

  • http://blogs.msdn.com/powershell/archive/2009/03/27/get-closure-with-getnewclosure.aspx
  • http://www.nivot.org/2009/03/28/PowerShell20CTP3ModulesInPracticeClosures.aspx


来源:https://stackoverflow.com/questions/1831955/powershell-an-elegant-way-to-create-closures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!