将函数作为参数传递 [英] Pass function as a parameter

查看:50
本文介绍了将函数作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了函数A",它将调用许多其他函数之一.为了节省重写函数'A',我想将要调用的函数作为函数'A'的参数传递.例如:

I've written function 'A' that will call one of a number of other functions. To save re-writing function 'A', I'd like to pass the function to be called as a parameter of function 'A'. For example:

function A{
    Param($functionToCall)
    Write-Host "I'm calling : $functionToCall"
}

function B{
    Write-Host "Function B"
}

Function C{
    write-host "Function C"
}

A -functionToCall C

返回:我打电话给:C

我期待它返回:我正在调用:函数 C.

I am expecting it to return: I'm calling: Function C.

我尝试了各种方法,例如:

I've tried various things such as:

Param([scriptblock]$functionToCall)

无法将 System.String 转换为 ScriptBlock

Cannot convert System.String to ScriptBlock

A -functionToCall $function:C

返回写主机"函数 C

A - functionToCall (&C)

这在它的其余部分之前进行评估:

This evaluates before the rest of it:

 Function C
 I'm Calling :

我确定这是编程 101,但我无法计算出正确的语法或我做错了什么.

I'm sure this is programming 101, but I can't work out the correct syntax or what it is I'm doing wrong.

推荐答案

这是您需要的吗?

function A{
    Param($functionToCall)
    Write-Host "I'm calling : $functionToCall"

    #access the function-object like this.. Ex. get the value of the StartPosition property
    (Get-Item "function:$functionToCall").ScriptBlock.StartPosition

}

function B{
    Write-Host "Function B"
}

Function C{
    write-host "Function C"
}


PS> a -functionToCall c

I'm calling : c


Content     : Function C{
                  write-host "Function C"
              }
Type        : Position
Start       : 307
Length      : 43
StartLine   : 14
StartColumn : 1
EndLine     : 16
EndColumn   : 2

这篇关于将函数作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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