奇数 C# 三元运算符行为

Odd C# Ternary Operator Behavior

所以我今天遇到了 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());
    ....
}

三元运算符接收 decimalif 语句发送 int。如下输出代码所示:

我认为自己是一个有一定天赋的程序员,今天这真的让我失望了。我用它玩了 2-3 个小时,并在此处找到了 post 的最佳方法,因此我清楚了我遇到的问题。

请避免使用“你为什么要那样做”这样的回复。我只是想知道为什么三元运算符和 if 语句之间存在差异。

我发现唯一另一个 post 密切相关的是这个,但它不太匹配:

Bizarre ternary operator behavior in debugger on x64 platform

三元运算符是一种 运算符,它只是一种特殊的方法。与任何其他方法一样,它只能有 一个 return 类型 .

您尝试做的是根据条件使用运算符 return decimal? int?。那是不可能的。

编译器知道存在从 int?decimal? 的隐式转换,但反之则不然。因此它将运算符 的 return 类型推断为 decimal? 并将您的 intValue 隐式转换为 decimal?.

三元表达式returns单一类型,不是以求值结果为条件的类型。

为了满足该要求,您的整数被提升为十进制。

如果无法应用转换,您将收到编译器错误。

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

https://msdn.microsoft.com/en-us/library/ty67wk28.aspx