.net - 你怎么称呼这些?[数组][字符串][整数]
问题描述
这些叫什么?在 powershell 中编写脚本时,我可以使用它们来设置或转换变量的数据类型,但是这个术语是什么?这些有官方文档吗?
例子:
$var = @("hello","world")
If ($var -is [array]) { write-host "$var is an array" }
解决方案
Don Cruickshank 的有用答案提供了一个难题,但让我尝试给出一个全面的概述:
就其本身而言,[<fullTypeNameOrTypeAccelerator>]
表达式是一种类型文字,即以的形式对.NET 类型的引用,这是对它所代表的类型System.Reflection.TypeInfo
的丰富反射来源。
<fullTypeNameOrTypeAccelerator>
可以是 .NET 类型的全名(例如[System.Text.RegularExpressions.Regex]
- 可以选择System.
省略前缀 ( [Text.RegularExpressions.Regex]
) 或 PowerShell类型加速器的名称(例如[regex]
)
类型文字也用于以下构造:
作为casts,如果可能的话,将 (RHS [1] ) 操作数强制为指定类型:
[datetime] '1970-01-01' # convert a string to System.DateTime
- 请注意,例如,PowerShell 强制转换比 C# 灵活得多,并且类型转换经常隐式发生- 请参阅此答案以获取更多信息。相同的规则适用于下面列出的所有其他用途。
作为类型约束:
作为and运算符的RHS
-is
-as
,用于类型测试和条件转换:-is
不仅测试确切的类型,还测试派生类型以及接口实现:# 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,分别指左侧和右侧的操作数。
[2] 从技术上讲,参数和常规变量之间没有真正的区别:类型约束在两种情况下的作用方式相同,但是参数变量在调用时自动绑定(分配给)后,通常不会被分配再来一次。
推荐阅读
- flutter - 如何在颤振中实现应用程序超时会话
- jquery - 即使使用了 bootstrap 4,bootstrap select 1.13.1 似乎也不起作用
- google-analytics - 为什么我们的页面级唯一事件低于相同页面的唯一页面浏览量?
- xml - xml 模式 - 具有一个元素的替换组出现不超过一次
- java - 动态生成一个 json 对象
- c# - AmbiguousMatchException:操作请求不明确
- postgresql - 插入到只有一个元素的自定义类型的表列
- ms-access - 我的语法工作而不是编写完整的控制地址。为什么?
- windows - 如何从 DLL 文件中获取一些基本信息?
- c++ - c++ 中没有 timeout_exception 吗?