jar*_*ler 0 c# ternary-operator
所以我今天在C#中遇到了本地三元运算符的一些非常令人困惑的行为.三元运算符正在向我正在调用的方法发送错误的数据类型.基本前提是我想将十进制值转换为intif 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);
}
Run Code Online (Sandbox Code Playgroud)
我打电话的方法ResultAdd是:
public void ResultAdd(int pResultID, object pResultValue)
{
if (pResultValue == null) { return; }
Console.WriteLine(this.TestInfo.TestNum + ": " + pResultValue.GetType());
....
}
Run Code Online (Sandbox Code Playgroud)
三元运营商收到decimal,而if语句发送int.如下面的输出代码所示:
我认为自己是一个合理人才的程序员,这真的让我今天回来了.我玩了2-3个小时,想出了最好的发布方式,所以我很清楚我遇到的问题.
请避免"为什么你甚至这样做"类型的回应.我只是想知道为什么三元运算符和if语句之间存在差异.
我发现的唯一一个密切相关的帖子就是这个帖子,但它并不完全匹配:
三元运算符是 - 一个运算符,它只是一种特殊的方法.和任何其他方法一样,它只能有一个返回类型.
什么你试图做的是使用运营商返回一个decimal? 或一int?对条件不同.这是不可能的.
什么情况是,编译器知道存在从一个隐式转换int?到decimal?,而不是倒过来.因此,推断操作的返回类型为decimal?和你的隐式转换intValue成一个decimal?.