脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - PowerShell - Windows Powershell强类型数组

Windows Powershell强类型数组

2020-06-22 10:55Powershell教程网 PowerShell

强类型数组可以理解为强制数据类型的数组,也就是一个数组里只包含一种数据类型,强制转换数组语法的优势就是如果使用分号代替逗号分隔值,PowerShell将每个值看作命令文本,PowerShell会执行它并且存储结果。

Powershell数组一般具有多态性,如果你不指定元素的具体类型,解释器会自动选择合适的类型存储每个元素。如果要统一限制所有元素的类型,可是使用类型名和一对方括号作为数组变量的类型。这样每当赋值时,会自动类型检查。如果目标数据类型不能转换成功,就会抛出一个异常。

?
1
2
3
4
5
6
7
8
9
10
PS C:Powershell> [int[]] $nums=@()
PS C:Powershell> $nums+=2012
PS C:Powershell> $nums+=12.3
PS C:Powershell> $nums+="999"
PS C:Powershell> $nums+="can not convert"
Cannot convert value "can not convert" to type "System.Int32". Error: "Input string was not in a correct format."
At line:1 char:6
+ $nums <<<< +="can not convert"
  + CategoryInfo     : MetadataError: (:) [], ArgumentTransformationMetadataException
  + FullyQualifiedErrorId : RuntimeException

延伸 · 阅读

精彩推荐