PowerShell 中的强类型引用?
Strongly typed references in PowerShell?
我知道我可以使用以下方法在 PowerShell 中为函数键入参数:
Param (
[int]$myIntParam
);
而且我知道我可以像这样通过引用传递:
Param (
[ref]$myRefParam
);
是否可以坚持引用是针对特定类型的?例如,它可以是 "reference to integer" 类型吗?就像在 C 中一样,我会 "pointer to integer" 为 "int*"...PowerShell 中有类似的东西吗?
我尝试用谷歌搜索,但找不到任何相关信息。
没有语法来指定 "reference-to-type",因为 ref
在 Powershell 中是它自己的类型,而不是其他类型的修饰符。但是,您可以使用脚本验证器来获得相同的结果。
function f {
param(
[ValidateScript({$_.Value.GetType() -eq [Int32]})]
[ref] $i
)
$i.value += 1
"New value is $($i.value)"
}
> $x = 5
> f ([ref]$x)
New value is 6
> $x
6
> $y = 'hello'
> f ([ref]$y)
Exception: Cannot validate argument on parameter 'i'.
我知道我可以使用以下方法在 PowerShell 中为函数键入参数:
Param (
[int]$myIntParam
);
而且我知道我可以像这样通过引用传递:
Param (
[ref]$myRefParam
);
是否可以坚持引用是针对特定类型的?例如,它可以是 "reference to integer" 类型吗?就像在 C 中一样,我会 "pointer to integer" 为 "int*"...PowerShell 中有类似的东西吗?
我尝试用谷歌搜索,但找不到任何相关信息。
没有语法来指定 "reference-to-type",因为 ref
在 Powershell 中是它自己的类型,而不是其他类型的修饰符。但是,您可以使用脚本验证器来获得相同的结果。
function f {
param(
[ValidateScript({$_.Value.GetType() -eq [Int32]})]
[ref] $i
)
$i.value += 1
"New value is $($i.value)"
}
> $x = 5
> f ([ref]$x)
New value is 6
> $x
6
> $y = 'hello'
> f ([ref]$y)
Exception: Cannot validate argument on parameter 'i'.