C#中的三元运算符 [英] Ternary Operator in C#

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

问题描述

有人可以告诉我使用三元运算符在幕后会发生什么吗?执行以下代码行:

Can anyone please explain to me what happens behind the scenes when you use ternary operator? does this line of code:

string str = 1 == 1 ? "abc" : "def";

是作为简单的if/else语句生成的吗?请考虑以下内容:

is generated as a simple if / else statement? Consider the following:

class A
{
}

class B : A
{
}

class C : A
{
}

现在使用三元表达式,如下所示:

Now using ternary expression as follows:

A a1 = 1 == 1 ? new B() : new C();

此错误甚至无法编译:

无法确定条件表达式的类型,因为在'ConsoleApp1.B'和'ConsoleApp2.C'之间没有隐式转换

Type of conditional expression cannot be determined because there is no implicit conversion between 'ConsoleApp1.B' and 'ConsoleApp2.C'

有人能阐明这一点吗?

推荐答案

条件运算符将根据是否存在转换来有效地使用第二个表达式的第一个表达式的类型-并且不考虑基数(否则它总是会一直转到 object ,允许这样做:?"hello":10 ).

The conditional operator will effectively use the type of the first expression for the second according to whether there is a conversion - and doesn't take into account bases (otherwise it would just always go to object allowing this: ? "hello" : 10).

在这种情况下,编译器是正确的-两种类型之间没有转换.添加强制转换,但是在第一个强制转换上-它会编译-(A)new B().

In this case, the compiler is correct - there is no conversion between the two types. Add a cast, however on the first one - and it'll compile - (A)new B().

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

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