Powershell中的Lambda表达式 [英] Lambda Expression in Powershell

查看:429
本文介绍了Powershell中的Lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中有一个代码,该代码使用lambda表达式将委托传递给方法.如何在PowerShell中实现此目标.例如,以下是C#代码:

I have a code in C# which uses lambda expressions for delegate passing to a method. How can I achieve this in PowerShell. For example the following is a C# code:

string input = "(,)(;)(:)(!)";
string pattern = @"\((?<val>[\,\!\;\:])\)";
var r = new Regex(pattern);
string result = r.Replace(input, m =>
    {
        if (m.Groups["val"].Value == ";") return "[1]";
        else return "[0]";
    });
Console.WriteLine(result);

这是没有lambda表达式的PowerShell脚本:

And this is the PowerShell script without the lambda-expression in place:

$input = "(,)(;)(:)(!)";
$pattern = "\((?<val>[\,\!\;\:])\)";
$r = New-Object System.Text.RegularExpressions.Regex $pattern
$result = $r.Replace($input, "WHAT HERE?")
Write-Host $result

注意:我的问题不是要解决此正则表达式问题.我只想知道如何将lambda表达式传递给在PowerShell中接收委托的方法.

Note: my question is not about solving this regular-expression problem. I just want to know how to pass a lambda expression to a method that receives delegates in PowerShell.

推荐答案

在PowerShell 2.0中,您可以使用脚本块({ some code here })作为委托:

In PowerShell 2.0 you can use a script block ({ some code here }) as delegate:

$MatchEvaluator = 
{  
  param($m) 

  if ($m.Groups["val"].Value -eq ";") 
  { 
    #... 
  }
}

$result = $r.Replace($input, $MatchEvaluator)

或直接在方法调用中:

$result = $r.Replace($input, { param ($m) bla })

提示:

您可以使用[regex]将字符串转换为正则表达式:

You can use [regex] to convert a string to a regular expression:

$r = [regex]"\((?<val>[\,\!\;\:])\)"
$r.Matches(...)

这篇关于Powershell中的Lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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