c# - 无法将类型 'int' 隐式转换为 'short'?

标签 c# .net

<分区>

我有 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;
        }
    }

除了我有 _used = _cap - _avail; 的部分抛出这个错误,Error

1 Cannot implicitly convert type 'int' to 'short'. An explicit conversion exists (are you missing a cast?)

最佳答案

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

_cap - _avail

这是有效的:

(int) _cap - (int) _avail

... 带有 int 结果。

当然,你可以只转换结果:

_used = (short) (_cap - _avail);

关于c# - 无法将类型 'int' 隐式转换为 'short'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13502475/

相关文章:

c# - 使用 StoryQ 修改或配置输出

c# - iTextSharp : table row gets pushed to new page if it doesn't fit on the current one

c# - 使用异步时未处理 SqlConnection

c# - C# 中的 DebugBreak() 等价物

.net - 从 javascript 调用 vb.net 类函数

c# - 如何列出所有加载的程序集?

c# - 如何让计时器运行 10 分钟然后禁用按钮?

c# - ResourceManager - 如何找到嵌入式资源文件所需的基本名称?

c# - 如何使关闭按钮像最小化一样工作 : C# Winforms

c# - 为什么在 MVC5 中 Optional 参数值会自动填充路由数据?