为什么我需要总结的投短此code? [英] Why do i need to wrap this code in a cast to short?
问题描述
如果我有一些code这样的:
If i have some code like the following:
short myShortA = 54;
short myShortB = 12;
short myShortC = (short)(myShortA - myShortB);
这两个操作数都是短裤和它进入一个短,为什么我一定要投它?
Both operands are shorts and it's going into a short so why do i have to cast it?
推荐答案
由于没有短 - 短操作符。这两个操作数提升为int类型。
Because there's no "short - short" operator. Both operands are promoted to int.
从C#3规范的第7.7.5:
From section 7.7.5 of the C# 3 spec:
在predefined减法运算符 在下面列出。运营商所有 从x减去y。
The predefined subtraction operators are listed below. The operators all subtract y from x.
-
整数加减:
Integer subtraction:
int operator –(int x, int y);
uint operator –(uint x, uint y);
long operator –(long x, long y);
ulong operator –(ulong x, ulong y);
在checked上下文中,如果差 结果类型的范围外, 则会引发System.OverflowException。
In a checked context, if the difference is outside the range of the result type, a System.OverflowException is thrown.
(再有就是浮点减法。)
(And then there's floating point subtraction.)
这篇关于为什么我需要总结的投短此code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!