[英]Int64 % Int32 gives Int64 result
long longVar = 100_000_000_000;
int intVar = int.MinValue;
long result = longVar % intVar;
In this example, why result should be long? 在此示例中,为什么结果应该很长? It cannot be more than Int32.MaxValue, why it was decided to make remainder Int64 in this operation?
它不能超过Int32.MaxValue,为什么决定在此操作中剩余Int64?
As per the C# specification only the following remainder operators are predefined for integer types: 根据C#规范,仅以下整数类型的余数运算符是预定义的:
int operator %(int x, int y);
uint operator %(uint x, uint y);
long operator %(long x, long y);
ulong operator %(ulong x, ulong y);
Hence in your case the compiler chooses the long(long, long)
version, and casts intVar
to long
automatically. 因此,在您的情况下,编译器选择
long(long, long)
版本,并自动将intVar
强制转换为long
。 Then the result is of type long
. 那么结果是
long
类型的。
Because if you try to use Int32 in this situation will be OverflowException(maybe). 因为如果您尝试在这种情况下使用Int32,将导致OverflowException(也许)。 And have any moments in which will be cast into bigger object.
并且在任何时刻都会被投射到更大的物体中。 For example:
例如:
int firstNumber = 10;
long secondNumber = 100;
var result = firstNumber + secondNumber;
(result - long) If you don't believe me you can check. (结果-长)如果您不相信我,可以进行检查。
This is due to the automatic cast to the parameter type of a specific method. 这是由于自动转换为特定方法的参数类型。 In your case, this is '%'.
您的情况是“%”。 In the case of the '+' sign, you can override the statement and specify your own implementation of this statement.
对于“ +”号,您可以覆盖该语句并指定您自己的语句实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.