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

标签 .net powershell terminology

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

例子:

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

最佳答案

Don Cruickshank's helpful answer提供了一个难题,但让我尝试给出一个全面的概述:

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

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

类型文字也用于以下结构:

  • 作为casts ,如果可能,将 (RHS[1]) 操作数强制为指定类型:

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

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

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

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

    • -is不仅测试确切的类型,还测试派生类型以及接口(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 类型的实例如果可能,并返回 $null否则:

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

[1] 在算子和数学方程的上下文中,常用首字母LHS和RHS,指left-hand sideright-hand side 操作数,分别。

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

关于.net - 你怎么称呼这些? [数组][字符串][整数],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66995217/

相关文章:

.net - Oracle 客户端 x32 和 x64 共存

powershell - 将枚举值传递给 PowerShell 中的函数

swift - 什么是 Objective C 运行时特性?

c# - 实时通讯

.net - 基于 .NET Framework 构建的 Linux Distro

powershell - "Changing property ' 创建数据 ' is not allowed."Azure Powershell

terminology - 模型驱动开发 vs 模型驱动架构 vs 模型驱动工程

java - 网络模式与非网络模式的区别

.net - Entity Framework 将某些 varchar 列的复合键错误地视为身份

azure - 获取-AzResourceGroup : 'this.Client.SubscriptionId' cannot be null