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);
解决方法
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.