这些叫什么?在 powershell 中编写脚本时,我可以使用它们来设置或转换变量的数据类型,但这个术语是什么?这些有官方文档吗?
例子:
$var = @("hello","world")
If ($var -is [array]) { write-host "$var is an array" }
Don Cruickshank 的有用答案 提供了一块拼图,但让我试着给出一个全面的概述:
就其本身而言,
[<fullTypeNameOrTypeAccelerator>]
表达式是一个类型文字,即以System.Reflection.TypeInfo
实例的形式引用.NET类型,这是反射的丰富来源在它代表的类型上。
<fullTypeNameOrTypeAccelerator>
可以是 .NET 类型的全名(例如,[System.Text.RegularExpressions.Regex]
- 可选择省略 System.
前缀 ([Text.RegularExpressions.Regex]
) 或 PowerShell 类型加速器的名称(例如, [regex]
)
类型文字自己被使用:
通常,通过::
,static member-access operator
访问static members(通常是方法);例如:
# Call the static 'Match' method of the [regex]
# (System.Text.RegularExpressions.Regex) type.
# -> '10'
[regex]::Match('A10', '\d+').Value
TypeInfo
实例的实例方法来
反映给定类型,每个类型文字都是;例如:
# Get the names of all .NET interfaces that the [regex]
# (System.Text.RegularExpressions.Regex) implements.
# -> 'ISerializable'
[regex].GetInterfaces().Name
也用于以下结构:
作为casts,convert(强制)(RHS[1])操作数为指定类型或construct一个实例,如果可能的话:
# Convert a string to [datetime] (System.DateTime).
# Equivalent to the following call:
# [datetime]::Parse('1970-01-01', [cultureinfo]::InvariantCulture)
[datetime] '1970-01-01'
# Construct a [regex] instance.
# The same as the following constructor call:
# [regex]::new('\d+')
$re = [regex] '\d+'
As 类型约束:
指定函数或脚本中的 参数 变量的类型:
function foo { param([datetime] $d) $d.Year }; foo '1970-01-01'
锁定regularvariable的类型以用于所有未来的分配:[2]
[datetime] $foo = '1970-01-01'
# ...
$foo = '2021-01-01' # the string is now implicitly forced to [datetime]
-is
和
-as
运算符的RHS,用于类型测试和条件转换:
-is
不仅测试确切类型,还测试derived 类型以及 interface 实现:
# Exact type match (the `Get-Date` cmdlet outputs instances of [datetime])
(Get-Date) -is [datetime] # $true
# Match via a *derived* type:
# `Get-Item /` outputs an instance of type [System.IO.DirectoryInfo],
# which derives from [System.IO.FileSystemInfo]
(Get-Item /) -is [System.IO.FileSystemInfo] # $true
# Match via an *interface* implementation:
# Arrays implement the [System.Collections.IEnumerable] interface.
1..3 -is [System.Collections.IEnumerable] # true
-as
将 LHS 实例转换为 RHS 类型的实例if possible,否则返回
$null
:
'42' -as [int] # 42
'foo' -as [int] # $null
[仅限 PowerShell v7.3+] 作为type arguments in generic method calls:
Enumerable.OfType<TResult>(IEnumerable)
[int]
作为其类型参数(从而请求仅返回该类型的可枚举元素):
# -> 2, 4
[System.Linq.Enumerable]::OfType[int](@('one', 2, 'three', 4))
about_Calling_Generic_Methods。
[1] 在运算符和数学方程的上下文中,通常使用缩写 LHS 和 RHS,分别指代left-hand side 和right-hand side 操作数。
[2] 从技术上讲,parameter 和 regular 变量之间没有真正的区别:类型约束在两种情况下的作用相同,但参数变量在 上自动绑定(分配)之后调用,通常不分配给again.
cast operator。官方文档在about_operators.中使用了这个术语
强制转换运算符 [ ]将对象转换或限制为指定类型。如果对象 无法转换,PowerShell 会产生错误。