Cannot implicitly convert type 'int' to 'short'?
本问题已经有最佳答案,请猛点这里访问。
我有三个变量都声明为类型"int16",但这段代码拒绝工作。
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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; } } |
除了我有
1 Cannot implicitly convert type 'int' to 'short'. An explicit conversion exists (are you missing a cast?)
是的,因为
1 | _cap - _avail |
这实际上是:
1 | (int) _cap - (int) _avail |
…有一个
当然,您可以将结果强制转换为:
1 | _used = (short) (_cap - _avail); |