微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐