如何以编程方式确定函数参数的默认值? [英] How can I programmatically determine the default value of a function parameter?

查看:86
本文介绍了如何以编程方式确定函数参数的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下功能:

function f {param($x = 42)}

$ x 的默认值为42.假设我有一堆函数,它们的参数除其他外,我要通过编程方式对其默认值进行测试.通过使用以下命令之一返回的对象,我还能发现其他事情:

$x has a default value of 42. Suppose I have a bunch of functions whose parameters I want to test programmatically for, among other things, their default values. Those other things I am able to discover using the objects returned using one of the following commands:

Get-Item function:/f | % Parameters | % x | % Attributes
Get-Help f | % Parameters | % parameter

这些命令输出以下内容:

Those commands output the following:

Position                        : 0
ParameterSetName                : __AllParameterSets
Mandatory                       : False
ValueFromPipeline               : False
ValueFromPipelineByPropertyName : False
ValueFromRemainingArguments     : False
HelpMessage                     : 
HelpMessageBaseName             : 
HelpMessageResourceId           : 
DontShow                        : False
TypeId                          : System.Management.Automation.ParameterAttribute

name             : x
required         : false
pipelineInput    : false
isDynamic        : false
parameterSetName : (All)
parameterValue   : Object
type             : @{name=Object}
position         : 0
aliases          : None

关于默认值似乎没有任何线索.

There doesn't seem to be any clue as to the default value.

如何以编程方式确定函数参数的默认值?

How can I programmatically determine the default value of a function parameter?

推荐答案

您可以使用语法树查找参数的默认值表达式.

You can use syntax tree to find default value expression for parameter.

function f {
    param(
        $x = 42,
        $y = 6*7,
        $z = (Get-Random)
    )
}

$Parameters = (Get-Item function:\f).ScriptBlock.Ast.Body.ParamBlock.Parameters
$xDefaultValue = $($Parameters.Where{$_.Name.VariablePath.UserPath -eq 'x'}).DefaultValue
$yDefaultValue = $($Parameters.Where{$_.Name.VariablePath.UserPath -eq 'y'}).DefaultValue
$zDefaultValue = $($Parameters.Where{$_.Name.VariablePath.UserPath -eq 'z'}).DefaultValue

然后可以使用语法树节点的 SafeGetValue()方法检索常量值,但不适用于表达式.

You can than use SafeGetValue() method of syntax tree node to retrieve constant value, but it does not work with expressions.

$xDefaultValue.SafeGetValue()
$yDefaultValue.SafeGetValue()
$zDefaultValue.SafeGetValue()

这篇关于如何以编程方式确定函数参数的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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