Lambda Expression in Powershell

前端 未结 3 1138
忘了有多久
忘了有多久 2020-11-27 04:43

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:

<         


        
相关标签:
3条回答
  • 2020-11-27 05:19

    Sometimes you just want something like this:

    {$args[0]*2}.invoke(21)
    

    (which will declare an anonymous 'function' and call it immediately.)

    0 讨论(0)
  • 2020-11-27 05:19

    You can use this overload

    [regex]::replace(
       string input,
       string pattern, 
       System.Text.RegularExpressions.MatchEvaluator evaluator
    )
    

    The delegate is passes as a scriptblock (lambda expression) and the MatchEvaluator can be accessed via the $args variable

    [regex]::replace('hello world','hello', { $args[0].Value.ToUpper() })
    
    0 讨论(0)
  • 2020-11-27 05:40

    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 })
    

    Tip:

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

    $r = [regex]"\((?<val>[\,\!\;\:])\)"
    $r.Matches(...)
    
    0 讨论(0)
提交回复
热议问题