在Powershell中,将字符串转换为int的惯用方法是什么?

Joh*_*ane 49 powershell

我发现的唯一方法是直接投射:

> $numberAsString = "10"
> [int]$numberAsString
10
Run Code Online (Sandbox Code Playgroud)

这是Powershell的标准方法吗?是否期望在之前进行测试以确保转换成功,如果是,如何?

Sha*_*evy 63

您可以使用-as运算符.如果铸造成功,你会得到一个数字:

$numberAsString -as [int]
Run Code Online (Sandbox Code Playgroud)

  • 实际上,如果转换失败,则返回$ null.如果然后将其转换为[int](隐式或显式),则得到0. (5认同)

CB.*_*CB. 57

使用.net

[int]$b = $null #used after as refence
$b
0
[int32]::TryParse($a , [ref]$b ) # test if is possible to cast and put parsed value in reference variable
True
$b
10
$b.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32                                    System.ValueType
Run Code Online (Sandbox Code Playgroud)

注意这个(powershell强制功能)

$a = "10"
$a + 1 #second value is evaluated as [string]
101 

11 + $a # second value is evaluated as [int]
21
Run Code Online (Sandbox Code Playgroud)


mjo*_*nor 13

是否会转换为[int]的快速真/假测试

[bool]($var -as [int] -is [int])
Run Code Online (Sandbox Code Playgroud)


JPB*_*anc 9

对我来说$numberAsString -as [int]@Shay Levy是最佳实践,我也使用[type]::Parse(...)[type]::TryParse(...)

但是,根据你的需要,你可以在算术运算符的右边放一个包含数字的字符串,左边是一个int,结果将是一个Int32:

PS > $b = "10"
PS > $a = 0 + $b
PS > $a.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32                                    System.ValueType
Run Code Online (Sandbox Code Playgroud)

您可以使用Exception(try/parse)在出现问题时表现


Man*_*ntz 5

我可能会做这样的事情:

[int]::Parse("35")
Run Code Online (Sandbox Code Playgroud)

但我并不是真正的 Powershell 人。它使用 System.Int32 中的静态 Parse 方法。如果无法解析字符串,它应该抛出异常。