用三元运算符动态 [英] dynamic with ternary operator

查看:86
本文介绍了用三元运算符动态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以及在下面的代码中如何工作

why and how this works in the below code

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

但不是这个

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

代码

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");
        }
    }


推荐答案

此与动态无关。这是因为在您的情况下,返回类型在其他情况下是不同的。

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.


由于
在'D1'和'D2'之间没有隐式转换,因此无法确定条件表达式的类型

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

对于三元运算符


first_expression和second_expression的类型必须与
相同,或者必须进行隐式转换存在从一种类型到另一种类型。

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.

这篇关于用三元运算符动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆