C#中的三元运算符关联性-我可以依靠它吗? [英] Ternary operator associativity in C# - can I rely on it?

查看:112
本文介绍了C#中的三元运算符关联性-我可以依靠它吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

啊,你不只是爱好三元虐待吗? :)考虑以下表达式:

Ahh, don't you just love a good ternary abuse? :) Consider the following expression:

true ? true : true ? false : false

对于现在完全困惑的那些人,我可以告诉你,这等于。换句话说,它等于:

For those of you who are now utterly perplexed, I can tell you that this evaluates to true. In other words, it's equivalent to this:

true ? true : (true ? false : false)

但这可靠吗?我可以确定在某些情况下不会出现这种情况吗?

But is this reliable? Can I be certain that under some circumstances it won't come to this:

(true ? true : true) ? false : false

有人可能会说-好吧,那就加括号然后不使用总共-毕竟,众所周知,三元运算符是邪恶的!

当然可以,但是在某些情况下它们确实有意义。对于那些好奇的人-我正在拧代码,按照一系列属性比较两个对象。如果我像这样冷写它,那就太好了:

Sure they are, but there are some circumstances when they actually make sense. For the curious ones - I'm wring code that compares two objects by a series of properties. It would be pretty nice if I cold write it like this:

obj1.Prop1 != obj2.Prop1 ? obj1.Prop1.CompareTo(obj2.Prop1) :
obj1.Prop2 != obj2.Prop2 ? obj1.Prop2.CompareTo(obj2.Prop2) :
obj1.Prop3 != obj2.Prop3 ? obj1.Prop3.CompareTo(obj2.Prop3) :
obj1.Prop4.CompareTo(obj2.Prop4)

简洁明了。但这确实取决于像在第一种情况下那样的三元算子关联性。括号只会使它成为意大利面条。

Clear and concise. But it does depend on the ternary operator associativity working like in the first case. Parenthesis would just make spaghetti out of it.

所以-是否在任何地方都指定了?我找不到它。

So - is this specified anywhere? I couldn't find it.

推荐答案

是的,您可以依靠它(不仅在C#中,而且在所有方面(我知道)带有条件运算符的其他语言( PHP …除外) ),而您的用例实际上是一种很常见的做法,尽管有人对此表示反对。

Yes, you can rely on this (not only in C# but in all (that I know) other languages (except PHP … go figure) with a conditional operator) and your use-case is actually a pretty common practice although some people abhor it.

ECMA-334(C#标准)的相关部分为14.13§3:

The relevant section in ECMA-334 (the C# standard) is 14.13 §3:


条件运算符是右关联的,这意味着运算从右到左分组。
[示例: a形式的表达式? b:c? d:e 被评估为 a? b:(c?d:e)。结束
示例]

The conditional operator is right-associative, meaning that operations are grouped from right to left. [Example: An expression of the form a ? b : c ? d : e is evaluated as a ? b : (c ? d : e). end example]

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

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