因此,我今天在C#中遇到了一些非常令人费解的本机三元算子的行为。三元操作符正在向我调用的方法发送错误的数据类型。基本的前提是,我希望将十进制值转换为int,如果是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
发布于 2016-06-24 16:38:07
三元算子是一个很好的算子,只是一种特殊的方法.与任何其他方法一样,它只能有一个返回类型的。
您要做的是使用操作符返回一个decimal? 或一个int?,这取决于一个条件。这是不可能的
所发生的情况是编译器知道有一个从int?到decimal?的隐式转换,但不是相反的。因此,它推断操作符的返回类型为decimal?,并隐式地将intValue转换为decimal?。
发布于 2016-06-24 16:38:44
三元表达式返回单个类型,而不是以计算结果为条件的类型。
为了满足这一要求,您的int被提升为十进制。
如果无法应用转换,您将得到一个编译器错误。
first_expression和second_expression的类型必须相同,或者必须存在从一种类型到另一种类型的隐式转换。
https://stackoverflow.com/questions/38018202
复制相似问题