2011-03-27 76 views
3

當我想劇本涉及兩個[unit32]變量,我得到了警告「錯誤:‘減法。價值是太大或太小,一個Int32’PowerShell減法是否將uint32值轉換爲int32內部?

的樣本來說明我所看到的

$v1 = [uint32]([int32]::MaxValue + 1) 
$v2 = [uint32]([int32]::MaxValue + 2) 
$v2 - $v1 

這是正常的行爲呢? 我怎樣才能避免錯誤?

回答

2

顯然PowerShell的算術總是簽署並不會轉化爲下一個更大的類型,如果有必要,確實如此。作爲一種變通方法,您可以使用[long]/[Int64]

PS> [long]$v2-$v1 
1 

或者只是聲明變量是[long]開始。

+0

PowerShell的將其轉換到下一個最大的類型,如果值不強類型。 – JasonMArcher 2011-03-28 16:27:52

5

你說得對,有點奇怪。但它書面方式的正確方法,是下面的,它的工作原理:

PS C:\> $v1 = [uint32]([int32]::MaxValue) + 1 
PS C:\> $v2 = [uint32]([int32]::MaxValue) + 2 
PS C:\> $v2 -$v1 
1 

的解釋是,([int32]::MaxValue + 1)是非感。如果你分解你的第一個情感,你可以看到轉換成雙。

PS C:\> $a = ([int32]::MaxValue + 1) 
PS C:\> $a.gettype() 

IsPublic IsSerial Name          BaseType 
-------- -------- ----          -------- 
True  True  Double         System.ValueType 

真奇怪的是,如果你只是添加一條線,它再次工作。

PS C:\> $v1 = [uint32]([int32]::MaxValue + 1) 
PS C:\> $v2 = [uint32]([int32]::MaxValue + 2) 
PS C:\> $v2 += 1 
PS C:\> $v2 - $v1 
2 

您可以調查這種表達與該cmdlet Trace-Command

PS C:\> Trace-Command -Name TypeConversion -Expression {[uint32]([int32]::MaxValue + 1)} -PSHost 
DÉBOGUER : TypeConversion Information: 0 : Converting "64" to "System.Int32". 
DÉBOGUER : TypeConversion Information: 0 :  Result type is assignable from value to convert's type 
DÉBOGUER : TypeConversion Information: 0 : Converting "System.Object[]" to "System.Object[]". 
DÉBOGUER : TypeConversion Information: 0 :  Result type is assignable from value to convert's type 
DÉBOGUER : TypeConversion Information: 0 : Conversion to System.Type 
DÉBOGUER : TypeConversion Information: 0 :  Conversion to System.Type 
DÉBOGUER : TypeConversion Information: 0 :   Found "System.Int32" in the loaded assemblies. 
DÉBOGUER : TypeConversion Information: 0 : Converting "2147483647" to "System.Double". 
DÉBOGUER : TypeConversion Information: 0 :  Numeric conversion succeeded. 
DÉBOGUER : TypeConversion Information: 0 : Converting "1" to "System.Double". 
DÉBOGUER : TypeConversion Information: 0 :  Numeric conversion succeeded. 
DÉBOGUER : TypeConversion Information: 0 : Conversion to System.Type 
DÉBOGUER : TypeConversion Information: 0 :  Conversion to System.Type 
DÉBOGUER : TypeConversion Information: 0 :   Found "System.UInt32" in the loaded assemblies. 
DÉBOGUER : TypeConversion Information: 0 : Converting "2147483648" to "System.UInt32". 
DÉBOGUER : TypeConversion Information: 0 :  Numeric conversion succeeded. 
2147483648 

大部分時間Trace-Command提供更多信息。

JP

相關問題