简体   繁体   English

三元运算符中的意外行为

[英]Unexpected behaviour in ternary operator

I came across a weird behavior when I changed an if-else to a ternary operator for a return statement. 当我将if-else更改为三元运算符以返回语句时,我遇到了一种奇怪的行为。

I've simplified the code here: 我在这里简化了代码:

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(), fooFalse.IfElseGet.GetType());
        }        
    }

The output from this is: 这个输出是:

System.Decimal, System.Decimal
System.Decimal, System.Int32

I'd expect the second row to output Int32 on both getters, but for the ternary I'm getting the incorrect CLR type back for the int. 我希望第二行在两个getter上输出Int32,但是对于三元组,我得到了不正确的CLR类型。

Never mind the code and what it's trying to do - I'm curious to why this is happening, so if anyone can explain it, I'd appreciate it. 不要介意代码和它正在尝试做什么 - 我很好奇为什么会发生这种情况,所以如果有人能够解释它,我会很感激。

Result of ternary (conditional) operator is always of single type - one/both of the options is casted to common type: 三元(条件)运算符的结果始终是单一类型 - 一个/两个选项都被转换为常见类型:

var result = condition ? decimalValue : intValue;

Type of result must be known statically at compile time. result类型必须在编译时静态知道。 Since there is cast from int to decimal than decimal type is selected as type of whole ? : 由于从intdecimal铸造比decimal类型被选为整体的类型? : ? : operator. ? :运营商。

So you whole function can be written as (showing automatic casts): 所以你可以将整个函数写成(显示自动强制转换):

public object TurnaryGet
{
    get
    {
        /*decimal*/ var result = condition ? decimalValue : (decimal)intValue;
        return (object)result;
    }
}
condition ? decimalValue : intValue;

means 手段

condition ? decimalValue : (decimal) intValue;

try if this work: (I'm stranger to C#, but this work in Java) 尝试这项工作:(我对C#很陌生,但这项工作是用Java编写的)

condition ? (object) decimalValue : (object) intValue;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM