Why do i need to wrap this code in a cast to short?

不打扰是莪最后的温柔 提交于 2019-12-23 09:48:32

问题


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?


回答1:


Because there's no "short - short" operator. Both operands are promoted to int.

From section 7.7.5 of the C# 3 spec:

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);
    

    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.)




回答2:


To make things a little bit easier, you could simply write an extension method like this:

public static class NumericExtensions
{
    public static short Subtract(this short target, short value)
    {
        return (short)(target - value);
    }
}

Others have answered your question... :)



来源:https://stackoverflow.com/questions/1547216/why-do-i-need-to-wrap-this-code-in-a-cast-to-short

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!