dynamic with ternary operator

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-30 07:11:15

问题


why and how this works in the below code

dynamic x = ( c== 'a') ? new D1() :x=  new D2();

but not this

dynamic x = ( c== 'a') ? new D1() : new D2();

Code

class Program
    {
        static void Main(string[] args)
        {
            var c = Console.ReadKey().KeyChar;
            dynamic x = ( c== 'a') ? new D1() :x=  new D2();
            x.Print();
            Console.ReadKey();
        }
    }    
    class D1
    {
        public void Print()
        {
            Console.WriteLine("D1");
        }
    }
    class D2
    {
        public void Print()
        {
            Console.WriteLine("D2");
        }
    }

回答1:


This has nothing to do with dynamic. This is because in your case the return type is not the same in case of Else.

If you write this statement instead, you will still get the same error.

var x = (c == 'a') ? new D1() : new D2();

However, if you write the following code you will succeed.

var c = 'd';
int a = 5;
decimal d = 6m;
decimal x = (c == 'a') ? a : d;

If you look at the error that you are getting, it is telling you the same thing.

Type of conditional expression cannot be determined because there is no implicit conversion between 'D1' and 'D2'

And For Ternary Operator

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.



来源:https://stackoverflow.com/questions/20995623/dynamic-with-ternary-operator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!