联合类型在 PowerShell 中可用吗

Tak*_*ARA 2 powershell

类型数组 like$arrIntOnly = [Int[]]@(1, 2, 3)可用于确保所有元素都是有效类型,但是否可以定义多种类型,例如$arrIntOrString = [[Int | String][]]@(1, "two", 3)?

mkl*_*nt0 5

只需使用 PowerShell 的默认数组,它们是[object[]]-typed,因此可以包含任何类型的组合:

# Note: @(...) around the array isn't strictly necessary.
$arrIntOrString = 1, 'two', 3
Run Code Online (Sandbox Code Playgroud)

没有直接的方法来限制允许的特定类型。

但是,您可以使用验证属性System.Management.Automation.ValidateScriptAttribute在本例中为 type)来强制元素仅限于指定类型:

[ValidateScript({ $_ -is [int] -or $_ -is [string] })] $arrIntOrString = 1, 'two', 3
Run Code Online (Sandbox Code Playgroud)

以上将在初始分配和以后的修改中强制执行指定的类型;例如,以下尝试稍后“添加” [1]非允许类型的元素将失败

# FAILS, because $true (of type [bool]) is neither an [int] nor [string]
$arrIntOrString += $true
Run Code Online (Sandbox Code Playgroud)

不幸的是,错误信息有点模糊: MetadataError: The variable cannot be validated because the value System.Object[] is not a valid value for the arrIntOrString variable.

请注意,此验证相当,因为{ ... }必须为每个元素执行一个脚本块 ( ) 。


[1] 数组是固定长度的数据结构,因此当您“添加”到数组时,PowerShell 所做的+=是在幕后创建一个数组,并附加新元素。数组的有效可扩展替代方案是非泛型System.Collections.ArrayList类型(例如,[System.Collections.ArrayList] (1, 'two', 3))和泛型System.Collections.Generic.List`1类型(例如,[System.Collections.Generic.List[object]] (1, 'two', 3))。然后使用.Add()方法添加到这些集合中;请注意,该ArrayList.Add()方法返回一个值,您可以使用$null = .... 要初始化任一类型的空集合,请@()转换为类型文字或调用其静态::new()方法。

  • @theberzi,不,PowerShell没有联合数据类型(我已经更新了答案以明确这一点),并且这个答案在_arrays_的上下文中提供了_approximation_,这就是问题所在。但是,您也可以将“ValidationScript”技术应用于参数声明 - 请参阅我的更新。 (2认同)