C#除法与可为空的十进制

c#

我有以下代码:

    decimal? Price = 36;
    decimal? ExchangeRate = 4.4m;
    decimal result = Price ?? 0 / ((ExchangeRate == 0) ? 1 : (ExchangeRate ?? 1));
    Console.WriteLine(result);
    //result = 36
    
    decimal cleanExchangeRate = ((ExchangeRate == 0) ? 1 : (ExchangeRate ?? 1));
    decimal cleanPrice = Price ?? 0;
    decimal result2 =  cleanPrice / cleanExchangeRate;
    Console.WriteLine(result2);
    //result2 = 8.18

第一次和第二次计算有什么区别?如果我把它作为单线来做,它不知何故不会划分价格。

回答

??具有非常低的优先级,所以单行被解析为:

Price ?? (0 / ((ExchangeRate == 0) ? 1 : (ExchangeRate ?? 1)));

如果Price为空,则计算为(0 / ((ExchangeRate == 0) ? 1 : (ExchangeRate ?? 1))),否则计算为Price

你可能是说

(Price ?? 0) / ((ExchangeRate == 0) ? 1 : (ExchangeRate ?? 1))

反而。


以上是C#除法与可为空的十进制的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>