且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

变量类型整数

更新时间:2023-11-30 22:50:22

如您所知:
As you already know:
sum = (Int16)(num1 + num2);
product = (Int16)(num1 * num2);


将工作. (除非结果大于Int16.MaxValue(32.768))

为所有数字类型( 8位和16位整数类型除外)定义了算术运算符(+,-,*,/,%). Int16是16位整数.因此,如果将两个Int16(或Int8等)相乘,则会使用32位算术运算符.这就是为什么结果是Int32的原因.

始终使用最大"数据类型的运算符.如果添加一个16Bit值和一个32bit值,它将返回一个32bit值.如果将32位值和64位值相乘,将返回64位值.

一些例子:


will work. (unless the result is greater than Int16.MaxValue (32.768))

The arithmetic operators (+, −, *, /, %) are defined for all numeric types except the 8- and 16-bit integral types. Int16 is a 16 bit integral. So if you multiply two Int16 (or Int8 etc) a 32bit arithmetic operator is used. And that is why the result is a Int32.

Operator for the "biggest" datatype is always used. If you add a 16Bit value and a 32bit value it will return a 32bit value. If you multiply a 32bit value and a 64bit value it will return a 64bit value.

some examples:

Int16 + Int32 = Int32
Int16 + Int64 = Int64
Int32 * Int32 = Int32
Int32 * Int64 = Int64




我认为这是运算符重载的问题,当运算符执行其工作时,它会返回一个inter值,因为Int16比Int32所需的内存空间少,因此无法直接进行强制转换,您可以使用一些自定义的 Implicit 明确投射
或使用
Hi,

I think this is a problem with Operator Overloading, when operator perform its job it return an inter value as Int16 is required less memory space then Int32 so it cant be cast directly you may use some custom Implicit or Explicit casting
or Use
Convert.ToInt16

进行转换.

不能直接投射,因此会引发错误.

但是,当您声明Int时,它将起作用.

to Convert it.

there for it cant be directly cast so its throwing an error.

But when you declare Int then its work.