首页 > 解决方案 > 如何使用变量的值作为转换类型?

问题描述

$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.

你如何让这个概念发挥作用?它可以为我节省一些空间。

标签: powershell

解决方案


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帮助文件以获取更多信息


特别是对于泛型类型,您还可以使用方法生成特定类型MakeGenericType(),参数的目标类型是[type[]]这样您的字符串将被隐式转换:

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

`末尾的数字表示类型参数的个数)


推荐阅读