小编lar*_*ust的帖子

三元运算符中的意外行为

当我将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)

.net c#

4
推荐指数
1
解决办法
108
查看次数

标签 统计

.net ×1

c# ×1