加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 01:47:34 所属栏目:百科 来源:网络整理
导读:在我的代码中,我有以下代码: Order = config.DeploymentSteps.Select(x = x.Order).DefaultIfEmpty().Max() + 1; 这给了我错误不能隐式地将类型’int’转换为’short’.作为参考订单和x.Order都是短路,Max()正确返回一个短(我已经验证了这一点).所以我明白
在我的代码中,我有以下代码:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读