Powershell中的数组类型-System.Object []与具有特定类型的数组 [英] Array Types In Powershell - System.Object[] vs. arrays with specific types

查看:83
本文介绍了Powershell中的数组类型-System.Object []与具有特定类型的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在字符串数组上标定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 []与具有特定类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆