当我将if-else更改为三元运算符以返回语句时,我遇到了一种奇怪的行为.
我在这里简化了代码:
class Foo
{
private bool condition;
private int intValue = 1;
private decimal decimalValue = 1M;
public object TernaryGet
{
get
{
return condition ? decimalValue : intValue;
}
}
public object IfElseGet
{
get
{
if (condition)
return decimalValue;
return intValue;
}
}
public Foo(bool condition)
{
this.condition = condition;
}
}
class Program
{
static void Main(string[] args)
{
var fooTrue = new Foo(true);
var fooFalse = new Foo(false);
Console.WriteLine("{0}, {1}", fooTrue.TernaryGet.GetType(), fooTrue.IfElseGet.GetType());
Console.WriteLine("{0}, {1}", fooFalse.TernaryGet.GetType(), …Run Code Online (Sandbox Code Playgroud)