你怎么称呼这些? [数组][字符串][整数]

What do you call these? [array][string][int]

这些叫什么?在 powershell 中编写脚本时,我可以使用它们来设置或转换变量的数据类型,但这个术语是什么?这些有官方文档吗?

示例:

$var = @("hello","world")
If ($var -is [array]) { write-host "$var is an array" }

它被称为强制转换运算符。官方文档在 about_operators.

中使用了这个术语

Cast operator [ ]

Converts or limits objects to the specified type. If the objects cannot be converted, PowerShell generates an error.

提供了一块拼图,但让我试着给出一个全面的概述:

本身,一个[<fullTypeNameOrTypeAccelerator>]表达式是一个类型文字,即以 System.Reflection.TypeInfo 实例的形式引用 .NET 类型 ,这是对其类型的 反射 的丰富来源代表.

<fullTypeNameOrTypeAccelerator> 可以是 .NET 类型的全名(例如,[System.Text.RegularExpressions.Regex] - optionally with the System. prefix omitted ([Text.RegularExpressions.Regex]) or the name of a PowerShell type accelerator(例如,[regex]

类型文字也用于以下结构

  • As casts,将 (RHS[1]) 操作数强制为指定的键入,如果可能的话:

    [datetime] '1970-01-01'  # convert a string to System.DateTime
    
    • 请注意,例如,PowerShell 转换比 C# 中的转换灵活得多,并且类型转换经常发生 隐式 - 有关详细信息,请参阅 。相同的规则适用于下面列出的所有其他用途。
  • 作为类型约束:

    • 指定函数或脚本中parameter变量的类型:

      function foo { param([datetime] $d) $d.Year }; foo '1970-01-01'
      
    • 锁定 常规 variable 的类型,用于所有未来的分配:[2]

      [datetime] $foo = '1970-01-01'
      # ...
      $foo = '2021-01-01' # the string is now implicitly forced to [datetime] 
      
  • 作为 -is-as 运算符 的 RHS,对于 type tests and conditional conversions:

    • -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 类型的实例 如果可能,并且 returns $null否则:

      '42' -as [int] # 42
      
      'foo' -as [int] # $null
      

[1] 在运算符和数学方程的上下文中,通常使用首字母缩写 LHS 和 RHS,指的是 左侧 右边操作数,分别为

[2] 从技术上讲,parameterregular 变量之间没有真正的区别:类型在这两种情况下,约束的功能相同,但参数变量在 调用 上自动绑定(分配)后,通常不会再次分配给 [=101] =].