问题描述
为什么在字符串数组上校准 GetType().Name
返回 Object[]
而不是 String[]
?这似乎发生在任何元素类型上,例如 Import-Csv
会给你一个 Object[]
但每个元素都是一个 PSCustomObject
.
Why does caling GetType().Name
on an array of strings return Object[]
and not String[]
?This seems to happen with any element type, for example Import-Csv
will give you an Object[]
but each element is a PSCustomObject
.
这是一个带有 String
$x = @('a','b','c')
$x[0].GetType().Name #String
$x.GetType().Name #Object[]
推荐答案
因为你没有明确指定数组的数据类型.
Because you have not specified the data type of the array explicitly.
例如,将整数分配给 $x[1]
会起作用,因为数组的类型是 Object[]
.
For instance, assigning an integer to $x[1]
would work, because the array's type is Object[]
.
如果在构造数组时指定数据类型,则以后将无法分配不兼容类型的值:
If you specify a data type while constructing the array, you won't be able to assign values of an incompatible type later:
C:\PS> [int[]] $myArray = 12,64,8,64,12
C:\PS> $myArray.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Int32[] System.Array
C:\PS> $myArray[0] = "asd"
Cannot convert value "asd" to type "System.Int32". Error: "Input string was not in a c
orrect format."
At line:1 char:1
+ $myArray[0] = "asd"
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastFromStringToInteger
这篇关于Powershell 中的数组类型 - System.Object[] 与具有特定类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!