gpt4 book ai didi

c# - 为什么我添加的 2 条短裤会因整数而导致类型转换编译错误?

转载 作者:行者123 更新时间:2023-11-30 14:16:28 26 4
gpt4 key购买 nike

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

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

这给我错误 Cannot implicitly convert type 'int' to 'short'。作为引用,Orderx.Order 都是短裤,Max() 正确返回一个 short(我已经验证了这一点)。所以我明白了,它认为 1 是一个 integer 并且出错了。所以我将其更改为:

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,而不转换整个内容?

最佳答案

因为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.

关于c# - 为什么我添加的 2 条短裤会因整数而导致类型转换编译错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7504837/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com