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

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

问题描述

基思·希尔解释我的块不关闭和创建一个块封我必须调用方法<一href="http://msdn.microsoft.com/en-us/library/system.management.automation.scriptblock.getnewclosure%28VS.85%29.aspx">.GetNewClosure().

有没有优雅的方式来创建一个块倒闭? (例如,创建一个包装函数,一个别名,......)

例如:

  {}块
$ {封}#???
 

解决方案

您可以创建一个函数,它接受一个脚本块,来电GetNewClosure并返回关闭。您在使用点运算符如调用这个函数,这是必不可少的:

 函数=&GT;([脚本块] $ _ sb_)
{
    $ _sb_.GetNewClosure()
}

函数A($块)
{
    B(=&GT; {写主机2;&安培; $块})
}

函数B($块){写主机1台;&安培; $块}

A {写主机3}
 

不知道这是不是只是调用GetNewClosure()的脚本块,虽然要好得多。请注意,你可以选择一些其他的函数名称。我要更多的东西,如C#lambda表达式。

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 } # ???

解决方案

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.

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

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