【发布时间】:2016-06-24 16:34:06
【问题描述】:
所以我今天在 C# 中遇到了原生三元运算符的一些非常莫名其妙的行为。三元运算符正在向我正在调用的方法发送错误的数据类型。基本前提是我想将十进制值转换为int if decimalEntry == false 这样它将作为int 存储在数据库中这是代码:
decimal? _repGroupResult = 85.00
int? intValue = null;
bool decimalEntry = false;
if (decimalEntry == false)
{
intValue = (int?) _repGroupResult;
}
Console.WriteLine("Sending to ResultAdd via ternary operator");
RepGBParent.ResultAdd(this.RepInfo.ResultID, decimalEntry ? _repGroupResult : intValue);
Console.WriteLine("Sending to ResultAdd via if statement");
// All other tests - just add the rep group result
if (decimalEntry)
{
RepGBParent.ResultAdd(this.RepInfo.ResultID, _repGroupResult);
}
else
{
RepGBParent.ResultAdd(this.RepInfo.ResultID, intValue);
}
我调用ResultAdd的方法在这里:
public void ResultAdd(int pResultID, object pResultValue)
{
if (pResultValue == null) { return; }
Console.WriteLine(this.TestInfo.TestNum + ": " + pResultValue.GetType());
....
}
三元运算符接收decimal,而if 语句发送int。如下输出代码所示:
我认为自己是一个具有合理天赋的程序员,这真的让我今天大吃一惊。我玩了 2 到 3 个小时,找到了在这里发布它的最佳方式,所以我很清楚我遇到的问题。
请避免“你为什么要那样做”类型的回复。我只是想知道为什么这里的三元运算符和if语句有区别。
我发现的唯一一个密切相关的帖子是这个,但它并不完全匹配:
Bizarre ternary operator behavior in debugger on x64 platform
【问题讨论】:
-
我讨厌人们这样做 if (bool == false)。使用 if(!bool) !!!但是没有 if(bool == true) 那样糟糕。
-
@JSON - 当人们来到这里并批评代码时,如果您从功能的角度使用
if (!bool)或if (bool == false),它会产生零差异,我讨厌它。这是个人喜好,简单明了,完全取决于可读性。有些人觉得!比== false更具可读性,有些人则不然。我个人觉得== false在查看代码时更容易理解。很容易错过一个!符号。
标签: c# ternary-operator