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.
你如何让这个概念发挥作用?它可以为我节省一些空间。
解决方案
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))
(`
末尾的数字表示类型参数的个数)
推荐阅读
- sql - 如果前面没有相同的字符,则替换字符
- php - Symfony 5.3 具有 OneToMany 关系的空集合
- amazon-web-services - 带有 API 网关的 AWS Lambda
- python - Python 读取文本文件格式
- python - layoutparser 给出错误“模块 layoutparser 没有属性 ocr”
- networking - 使用 Scapy 放大创建 NTP 查询数据包
- asp.net - 使用条件时,ASP.NET webforms 不会在 gridview 中检索查询
- go - 在 SAML v2.0 中,IDP 和 SP 之间的信任如何工作?
- javascript - joi 验证数组对象的每个项目必须具有相同的值
- julia - 为什么这个参数构造函数只适用于多行定义?