不能隐式地将类型'int'转换为'short'?

age*_*154 4 .net c#

我有3个变量都声明为'Int16'类型,但这段代码拒绝工作.

    private Int16 _cap;                 // Seat Capacity
    private Int16 _used;                // Seats Filled
    private Int16 _avail;               // Seats Available

    public Int16 SeatsTotal {
        get {
            return _cap;
        }
        set {
            _cap = value;
            _used = _cap - _avail;
        }
    }
Run Code Online (Sandbox Code Playgroud)

除了我所在的部分_used = _cap - _avail;抛出此错误,错误

1无法将类型'int'隐式转换为'short'.存在显式转换(您是否错过了演员?)

Jon*_*eet 8

是的,那是因为short(Int16)没有减法运算符.所以当你写:

_cap - _avail
Run Code Online (Sandbox Code Playgroud)

那是有效的:

(int) _cap - (int) _avail
Run Code Online (Sandbox Code Playgroud)

...... int结果.

当然,您可以投射结果:

_used = (short) (_cap - _avail);
Run Code Online (Sandbox Code Playgroud)

  • 你应该使用`(short)`或`Convert.Int16()`? (2认同)