gpt4 book ai didi

powershell - PowerShell 减法是否在内部将 uint32 值转换为 int32?

转载 作者:行者123 更新时间:2023-12-04 17:57:36 26 4
gpt4 key购买 nike

当我想编写涉及两个 [unit32] 变量的减法脚本时,我收到警告“错误:“值对于 Int32 来说太大或太小。”

一个例子来说明我所看到的

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

这是正常行为吗?
我怎样才能避免错误?

最佳答案

你说得对,这有点奇怪。但正确的写法如下,它有效:

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提供更多信息。

J.P

关于powershell - PowerShell 减法是否在内部将 uint32 值转换为 int32?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5448749/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com