为什么这种转换不能像C#一样在Powershell中工作?

时间:2019-05-06 22:06:20

标签: c# powershell types

我正在尝试将计算值转换为uint16。为了这个例子,我已经进行了硬编码。在C#中有效。但是,我认为Powershell中的相同代码失败了。请考虑以下内容:

在powershell代码示例中,它产生:

Cannot convert value "101398986" to type "System.UInt16". Error: "Value was either too large or too small for a UInt16."
At D:\OneDrive\Desktop\VaribleCasting2.ps1:2 char:1
+ [uint16]$v = [uint16]$g
+ ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastIConvertible

我尝试了[convert] :: ToUInt16($ g)它产生的结果:

Exception calling "ToUInt16" with "1" argument(s): "Value was either too large or too small for a UInt16."
At D:\OneDrive\Desktop\VaribleCasting2.ps1:2 char:1
+ [uint16]$v = [convert]::ToUInt16($g)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : OverflowException

PowerShell(失败):

$g = 101398986
[uint16]$v = [uint16]$g
$v

C#(成功):

using System;

namespace NumericTypeTesting
{
    class Program
    {
        static void Main(string[] args)
        {
            var g = 101398986;
            UInt16 v = (UInt16)g;
            Console.WriteLine(v);
            Console.ReadLine();
        }
    }
}

我期望两个平台中的.NET都能产生相同的结果。感谢您的帮助!

2 个答案:

答案 0 :(得分:5)

与C#不同,Powershell默认情况下会检查算术(例如Visual Basic)。这意味着默认情况下,您确实会在溢出时获取OverflowException,而不是在运行时默默地截断结果。

您可能希望查看How to suppress overflow-checking in PowerShell?以获得更多详细信息。

答案 1 :(得分:0)

您正在尝试将16位整数赋予数字101398986,这完全是不可能的,只要您使用的是16位,导致16位整数必须小于或等于65,535

或者如果其有符号整数:-32,767 <数字<32,767

因此,最好使用32位整数:

var g = 101398986;
UInt32 v = (UInt32)g;

您的数字必须小于或等于4294967295(对于32位整数)

相关问题