为什么我加入2短路引起铸造编译错误,由于整数? [英] Why is my addition of 2 shorts causing a casting compile error due to ints?

查看:86
本文介绍了为什么我加入2短路引起铸造编译错误,由于整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my code i have the following code:

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

这给我的错误无法隐式转换类型'诠释'到'短。作为一个参考订单 x.Order 都是短裤,和 MAX()正确返回(我已经验证了这一点)。所以,我得到它,它认为 1 整数和示数。所以,我把它改为:

This gives me the error Cannot implicitly convert type 'int' to 'short'. As a Reference Order and x.Order are both shorts, and Max() is correctly returning a short (I have verified this). So I get it, it thinks the 1 is an integer and erroring. So I changed it to:

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



我现在仍然得到相同的编译。因此,也许它不是铸造是正确的,所以我试图将其更改为

I'm now still getting the same compile. So maybe it's not casting it right, so I tried changing it to

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



但我仍然得到同样的错误。最后,我把它通过将整个表达式的工作:

Yet I still get the same error. Finally I got it to work by converting the whole expression:

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



为什么我不能投了1到,并将其添加到另一个短,无铸造整个事情?

Why can't I cast the 1 to a short and add it to another short, without casting the whole thing?

推荐答案

这是因为短+短= INT。

It is because short + short = int.

埃里克利珀解释了它的这里

Eric Lippert explains it here.

他说:

为什么短加上短期结果INT

Why is short plus short result in int?

好吧,假设短期加短很短,看看会发生什么:

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

短[] =价格10000 {,15000,11000};短期平均=(价格[0] +
价格[1] +价格[2])/ 3;平均,当然,如果-9845
此计算短裤完成。总和大于最大
可能短大,因此它绕到负,然后除以
中的负数。

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.

在一个世界在整数运算环绕它更
明智的做INT所有的计算,一类是有可能
具有足够的范围,典型的计算,不会溢出。

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.

这篇关于为什么我加入2短路引起铸造编译错误,由于整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆