我见过this ,但两个答案实际上都没有在调用函数时使用命名参数回答问题
这适用于 Powershell 7。没有工作流程。这次真的是命名参数!也未包含在标准文档中 here .. 开始认为这是不可能的。
这是有效的,但它需要带有位置参数的括号,而不是命名参数
Function MyFunction ([ref][string]$MyRefParam) {
$MyRefParam.Value = "newValue";
}
$myLocal = "oldValue"
Write-Host $myLocal # Outputs: oldValue
MyFunction ([ref]$myLocal);
Write-Host $myLocal # Outputs: newValue
当然,我们都知道调用 Powershell 函数的最佳方式是使用命名参数 MyFunction -Arg1 23
而不是位置参数 MyFunction 23
或 MyFunction(23)
.这些不会通过我们的拉取请求!但这不起作用
Function MyFunction ([ref][string]$MyRefParam) {
$MyRefParam.Value = "newValue";
}
$myLocal = "oldValue"
Write-Host $myLocal # Outputs: oldValue
MyFunction -MyRefParam ([ref]$myLocal) # Outputs Cannot process argument transformation on parameter 'MyRefParam'. Reference type is expected in argument.
Write-Host $myLocal # Outputs: oldValue
是否有另一种方法可以在此语法中提供 ref 类型?到目前为止,我已经在参数定义和调用中尝试了 [ref] 和 [ref][string] 的组合 - 我无法得到任何东西让 Powershell 看到我真的传递了一个 Ref谢谢你的帮助!
最佳答案
仅使用 [ref]
在参数声明中输入约束 ,即删除额外的 [string]
类型约束(它不做任何事情,甚至不应该被允许 - 见底部):
Function MyFunction ([ref] $MyRefParam) {
$MyRefParam.Value = "newValue"
}
$myLocal = 'oldVaue'
MyFunction -MyRefParam ([ref] $myLocal)
$myLocal # -> 'newvalue'
您不能输入 [ref]
实例:[ref]
不是修改参数声明的关键字(如 ref
在 C# 中),它本身就是一种类型, System.Management.Automation.PSReference
,及其保值属性,.Value
类型为 object
,即它可以容纳任何类型的对象。结果:
[ref]
传递时,您不能强制执行特定的数据类型。 .[1].Value
分配任何类型的值。 [ref]
的属性(property)实例收到。退一步 :
[ref]
主要用于支持对 .NET API 的调用 与 ref
/out
参数。也就是说,位置和命名参数绑定(bind)之间的双重类型约束的行为差异当然很奇怪 - 见 Mathias R. Jessen's评论中有很好的解释。
然而,真正的问题是,您甚至可以定义涉及
[ref]
的多类型约束(本身不寻常)。 ,因为似乎有一个有意的检查来防止这种情况发生,但它并没有出现在参数声明中。但是,您可以使其显示如下(直接在命令行中运行):
# ERROR, because [ref] cannot be combined with other type constraints.
PS> [ref] [string] $foo = 'bar'
Cannot use [ref] with other types in a type constraint
在 GitHub issue #16146 中报告了在参数声明中没有强制执行相同的检查。 .[1] 在幕后,当实际值通过
[ref]
传递时,会使用非公开的泛型类型。 cast ( System.Management.Automation.PSReference<T>
),它使用被转换的值的任何类型实例化。然而,这个泛型类型的 .Value
属性(property)还在[object]
-typed,允许修改以分配任何类型。
关于powershell - 如何在 PowerShell 中将 "named"参数定义为 [ref](这次是真的),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69306144/