Tod*_*odd 1 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
Run Code Online (Sandbox Code Playgroud)
我试过[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
Run Code Online (Sandbox Code Playgroud)
PowerShell(失败):
$g = 101398986
[uint16]$v = [uint16]$g
$v
Run Code Online (Sandbox Code Playgroud)
C#(成功):
using System;
namespace NumericTypeTesting
{
class Program
{
static void Main(string[] args)
{
var g = 101398986;
UInt16 v = (UInt16)g;
Console.WriteLine(v);
Console.ReadLine();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的期望是,在两个平台上的.NET都会产生相同的结果。谢谢你的帮助!
小智 5
与C#不同,Powershell默认情况下会检查算法(例如Visual Basic)。这意味着默认情况下,当您溢出时,您确实会获得OverflowException,而不是运行时以静默方式截断结果。
您可能想看看如何抑制PowerShell中的溢出检查?更多细节。
| 归档时间: |
|
| 查看次数: |
63 次 |
| 最近记录: |