奇数C#三元运算符行为

时间:2016-06-24 16:34:07

标签: c# ternary-operator

所以我今天在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。如下面的输出代码所示:

enter image description here

我认为自己是一个合理人才的程序员,这真的让我今天回来了。我玩了2-3个小时,想出了最好的发布方式,所以我很清楚我遇到的问题。

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

我发现的唯一一个密切相关的帖子就是这个帖子,但它并不完全匹配:

Bizarre ternary operator behavior in debugger on x64 platform

2 个答案:

答案 0 :(得分:8)

三元运算符 - 是 - 运算符,它只是一种特殊的方法。和任何其他方法一样,它只能有一个返回类型

您尝试执行的操作是根据条件使用运算符返回decimal? int?。这是不可能的。

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

答案 1 :(得分:4)

三元表达式返回单个类型,而不是以评估结果为条件的类型。

你的int被提升为十进制,以满足这个要求。

如果无法应用转换,则会出现编译错误。

  

first_expression和second_expression的类型必须相同,或者从一种类型到另一种类型必须存在隐式转换。

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

相关问题