c# – 为什么我添加了2个短片导致由于整数引起的转换编译错误?

在我的代码中,我有以下代码

Order = config.DeploymentSteps.Select(x => x.Order).DefaultIfEmpty().Max() + 1;

这给了我错误不能隐式地将类型’int’转换为’short’.作为参考订单和x.Order都是短路,Max()正确返回一个短(我已经验证了这一点).所以我明白了,它认为1是一个整数并且错误.所以我改成了:

Order = config.DeploymentSteps.Select(x => x.Order).DefaultIfEmpty().Max() + (short)1;

我现在仍然得到相同的编译.所以也许它不是正确的,所以我尝试将它改为

Order = config.DeploymentSteps.Select(x => x.Order).DefaultIfEmpty().Max() + Convert.ToInt16(1);

但我仍然得到同样的错误.最后我通过转换整个表达式来实现它:

Order = Convert.ToInt16(config.DeploymentSteps.Select(x => x.Order).DefaultIfEmpty().Max() + 1);

为什么我不能把1加到一个简短的并将它添加到另一个简短的,而不是整个东西?

解决方法

这是因为short short = int.

Eric Lippert解释它here.

他说:

Why is short plus short result in int?

Well,suppose short plus short was short and see what happens:

short[] prices = { 10000,15000,11000 }; short average = (prices[0] +
prices[1] + prices[2]) / 3; And the average is,of course,-9845 if
this calculation is done in shorts. The sum is larger than the largest
possible short,so it wraps around to negative,and then you divide
the negative number.

In a world where integer arithmetic wraps around it is much more sensible to do all the calculations in int,a type which is likely to have enough range for typical calculations to not overflow.

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...