简体   繁体   English

将js转换为C#时出现System.OverflowException

[英]System.OverflowException in converting js to C#

var pin = parseInt(form.mac.value.slice(-6), 16) % 10000000;

I'm convert the JS to C# like this 我像这样将JS转换为C#

var pin = Convert.ToInt16(Networks[NetworkIndex, 0].Substring(Networks[NetworkIndex, 0].Length - 6)) % 10000000;

and then I get this error 然后我得到这个错误

An unhandled exception of type 'System.OverflowException' occurred in mscorlib.dll Additional information: Value was either too large or too small for an Int16. mscorlib.dll中发生了'System.OverflowException'类型的未处理异常。其他信息:对于Int16,值太大或太小。

The value is too big for Int16 . 对于Int16该值太大。 Try to use Convert.ToInt32 . 尝试使用Convert.ToInt32

var pin = Convert.ToInt32(Networks[NetworkIndex, 0].Substring(Networks[NetworkIndex, 0].Length - 6)) % 10000000;

Use Convert.ToInt32 instead of Convert.ToInt16 . 使用Convert.ToInt32而不是Convert.ToInt16 The value is too big to fit in Int16 . 该值太大,无法放入Int16

The Int16 value type represents signed integers with values ranging from negative 32768 through positive 32767 . Int16值类型表示带符号整数,其值范围从负32768到正32767 307650 is way bigger than 32767 so you should use a bigger type to store the value in. Int16 uses 2 bytes of memory to store integral value, Int32 will use 4 bytes and can manage to store a bigger range of integers. 30765032767大得多,因此您应使用更大的类型来存储值Int16使用2个字节的内存来存储整数值, Int32将使用4个字节并可以存储更大范围的整数。 Int32 is an immutable value type that represents signed integers with values that range from negative 2,147,483,648 through positive 2,147,483,647. Int32是一个不可变的值类型,表示带符号的整数,其值的范围从负2147483648至正2147483647。

Try this one 试试这个

var pin = Convert.ToInt32(Networks[NetworkIndex, 0].Substring(Networks[NetworkIndex, 0].Length - 6)) % 10000000;

You can also use int.TryParse("your number", out int) This will not throw any exception(When you'll get null in string.). 您还可以使用int.TryParse("your number", out int)这不会引发任何异常(当字符串中为null时。)。 If it is parsed then it means the value is correct or you can explicitly throw exception from your code. 如果对其进行了解析,则表示该值正确,或者您可以从代码中显式引发异常。

Take a look. 看一看。

Int.TryParse 尝试解析

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM