关于类型转换的困惑

时间:2019-05-02 21:21:35

标签: powershell

我写了一个计算阶乘的函数。试图确保当输入值不是整数,但PowerShell自动转换输入时会给出错误。有没有一种方法可以确保捕获到非整数并显示错误。

function Get-Factorial ([int]$x) {
    if ($x -isnot [system.int32]) {
        return "error"
    }
    if ($x -eq 0) {
        return 1
    }
    return $x * (Get-Factorial($x - 1))
}

1 个答案:

答案 0 :(得分:0)

当然,不要告诉Powershell您想要[int]作为第一个参数

function Get-Factorial ($x) {
    if($x -isnot [system.int32]){
       throw [System.ArgumentException]
    }
    if ($x -eq 0) {
        return 1
    }
             return $x * (Get-Factorial($x - 1))
}

PS C:\Users\jos> Get-Factorial -x 1.1 
System.ArgumentException
At line:1 char:1
+ throw [System.ArgumentException]
…
# or 
PS C:\Users\jos> Get-Factorial 1.1 
System.ArgumentException
At line:1 char:1
+ throw [System.ArgumentException]
...

相关问题