三元运算符行为不一致 [英] Ternary operator behaviour inconsistency

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

问题描述

以下表达式可以

short d = ("obj" == "obj" ) ? 1 : 2;

但是当您使用它时,语法错误发生

But when you use it like below, syntax error occurs

short d = (DateTime.Now == DateTime.Now) ? 1 : 2;

无法将类型'int'隐式转换为'short'。存在显式转换(您是否错过了演员?)

Cannot implicitly convert type 'int' to 'short'. An explicit conversion exists (are you missing a cast?)

有人可以解释为什么会这样吗?

Can anyone explain why this is so?

在三元运算符中比较字符串到字符串和日期时间到日期时间之间有区别吗,为什么?

Is there a difference between comparing string-to-string and datetime-to-datetime in a ternary operator, why?

如果您能帮助我,我将不胜感激。

I would be grateful if you could help me.

推荐答案

C#语言规范,版本5 ,第6.1.9节:


隐式常量表达式转换允许以下转换:

An implicit constant expression conversion permits the following conversions:


  • int类型的常量表达式(第7.19节)可以转换为sbyte,byte,short类型,ushort,uint或ulong,前提是constant-expression的值在目标类型的范围内。

您的第一个示例一个常量表达式,因为它可以在编译时进行评估。但有关更多详细信息,请参阅第7.19节:

Your first example is a constant expression, because it can be evaluated at compile time. But see section 7.19 for more details:


在常量表达式中只允许使用以下结构:

Only the following constructs are permitted in constant expressions:


  • 文字(包括空文字)。

[...]



  • 预定义的+, - ,*,/,%,<< ;,>>,&,|,^,&&,||,==,!=,<,>,< =和> =二元运算符,前提是每个操作数都是上面列出的类型。

  • ?:条件运算符。

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

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