如何使用变量的值作为转换类型?

时间:2018-08-19 19:55:36

标签: powershell

$myType="string"
[$myType]$myArray="hello","world"

我得到Missing type name after '['.

$myType="string"
[System.Collections.ObjectModel.ReadOnlyCollection[$myType]]$myCollection

我得到Unexpected token '$myType' in expression or statement.

您如何使这个概念起作用?它可以为我节省一些空间。

1 个答案:

答案 0 :(得分:3)

PowerShell 3.0引入了-as未经检查的转换运算符,它将为您将类型名称转换为类型:

$myType = 'string[]'
$numbers = 1,2,3 -as $myType

$myType = 'string'
$readOnlyStrings = @('some','strings') -as "System.Collections.ObjectModel.ReadOnlyCollection[$myType]"

有关about_Type_Operators help file的更多信息,请查看


特别是对于泛型类型,您也可以generate a specific type using the MakeGenericType() method,参数的目标类型是[type[]],因此您的字符串将被隐式转换:

$myType = 'string'
$readOnlyType = [System.Collections.ObjectModel.ReadOnlyCollection`1].MakeGenericType(@($myType))

`后面的数字表示类型参数的数量)