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

查看:41
本文介绍了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)

或者直接在方法调用中:

Or directly in the method call:

$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天全站免登陆