方法调用失败,因为 [System.Object[]] 不包含名为"op_Division"的方法



我想构建一个函数,但我收到错误,说我无法进行除法。 有趣的是,在函数之外是可能的。

function Resolution2AspectRatio($Width, $Height) {
$tmp = $Width/$Height
return $tmp
}
[System.Windows.Forms.Screen]::AllScreens | Select Bounds, Primary | ForEach-Object {
$DisplayWidth = [int]$_.Bounds.Width
$DisplayHeight = [int]$_.Bounds.Height
Write-Host $($DisplayWidth/$DisplayHeight)
Write-Host $(Resolution2AspectRatio($DisplayWidth, $DisplayHeight))
}

知道如何解决这个问题吗?

每当某些东西在函数外部工作,但在函数内部不起作用时,请查看您如何调用该函数以及传递的参数的类型/值。

在这种情况下,部分问题在于您在 Write-Host 行中调用函数的方式。 通过将参数放在括号内并用逗号分隔它们,你告诉 PowerShell 这两个值是整数的 2 元素数组,应传递给第一个参数。 由于您没有在函数中声明变量的类型,因此该类型被接受,并且您的第二个参数仍为空。

我添加了两个 Write-Host 语句,供您在参数变量传递后查看它们的值,以及调用函数的"正确"和"错误"方式。

function Resolution2AspectRatio($Width, $Height) {
Write-Host "Width = $Width"
Write-Host "Height = $Height"
$tmp = $Width / $Height
return $tmp
}
[System.Windows.Forms.Screen]::AllScreens | Select Bounds, Primary | ForEach-Object {
$DisplayWidth = [int]$_.Bounds.Width
$DisplayHeight = [int]$_.Bounds.Height
Write-Host $($DisplayWidth/$DisplayHeight)
#Wrong way to call function
Write-Host $(Resolution2AspectRatio($DisplayWidth,$DisplayHeight))
#Right way to call function
Write-Host $(Resolution2AspectRatio $DisplayWidth $DisplayHeight)
}

相关内容

最新更新