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

问题描述 投票:0回答:2

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

例子:

$var = @("hello","world")
If ($var -is [array]) { write-host "$var is an array" }
.net powershell terminology
2个回答
6
投票

Don Cruickshank 的有用答案 提供了一块拼图,但让我试着给出一个全面的概述:

就其本身而言,

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

<fullTypeNameOrTypeAccelerator>
可以是 .NET 类型的全名(例如,
[System.Text.RegularExpressions.Regex]
- 可选择省略
System.
前缀 (
[Text.RegularExpressions.Regex]
) 或 PowerShell 类型加速器的名称(例如,
[regex]
)


类型文字自己被使用:


类型文字

用于以下结构

  • 作为castsconvert(强制)(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:


[1] 在运算符和数学方程的上下文中,通常使用缩写 LHS 和 RHS,分别指代left-hand sideright-hand side 操作数。

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


4
投票
它被称为

cast operator。官方文档在about_operators.中使用了这个术语

强制转换运算符 [ ]

将对象转换或限制为指定类型。如果对象 无法转换,PowerShell 会产生错误。

© www.soinside.com 2019 - 2024. All rights reserved.