由于某种原因,powershell 不允许我将 a 转换string[]
为 an,object[]
但允许将所有其他类型转换为 an。下面的示例显示它适用于除字符串之外的几种类型。
[int[]]$intary = 2,4
[char[]]$chrary = 'a','b'
[bool[]]$booary = $true,$false
[DateTime[]]$datary = (Get-Date),(Get-Date)
[string[]]$strary = 'c','d'
$splary = 'e,f' -split ',' # -split returns [string[]] type specifically
[object[]]$objaryi = @()
[object[]]$objaryc = @()
[object[]]$objaryb = @()
[object[]]$objaryd = @()
[object[]]$objarys = @()
[object[]]$objarysp = @()
$intary.GetType() # Int32[]
$chrary.GetType() # Char[]
$booary.GetType() # Boolean[]
$datary.GetType() # DateTime[]
$strary.GetType() # String[]
$splary.GetType() # String[]
$objaryi.GetType() # Object[]
'conversions'
$objaryi = $intary # Int32[] converted to Object[]
$objaryi.GetType() # Object[]
$objaryc = $chrary # Char[] converted to Object[]
$objaryc.GetType() # Object[]
$objaryb = $booary # Boolean[] converted to Object[]
$objaryb.GetType() # Object[]
$objaryd = $datary # DateTime[] converted to Object[]
$objaryd.GetType() # Object[]
$objarys = $strary # NOT converted to Object[]; instead changes type of $objarys to String[]
$objarys.GetType() # String[]
$objarysp = $splary # NOT converted to Object[]; instead changes type of $objarysp to String[]
$objarysp.GetType() # String[]
$objarys = @($strary) # the array subexpression operator @() DOES convert to Object[]
$objarys.GetType() # Object[]
$objarysp = @($splary) # the array subexpression operator @() DOES convert to Object[]
$objarysp.GetType() # Object[]
'inline cast'
$objarys = @([string[]]@(1,2)) # the array subexpression operator @() does not work on an inline cast [1]
$objarys.GetType() # String[]
这很重要的一个原因是,如果您尝试将哈希存储在类型为string[]
powershell 的数组中,则会默默地将您的哈希定义转换为字符串。该字符串是哈希的完整路径类型名称的字符串。
$objaryi[0] = @{a=1;b=2} # can hold a hashtable because it's now an Object[]
$objaryi[0].GetType() # Hashtable
$objaryi[0]['b'] # 2
$objarys[0] = @{a=1;b=2} # silently converts to a string because it's a String[]
$objarys[0].GetType() # String
$objarys[0]['b'] # $null; perhaps unexpected
$objarys[0] # the String value "System.Collections.Hashtable"
$objarys[0].Length # 28