2011-03-27 52 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