[英]How to rewrite multiple ternary “? :” in terms of “if” statements?
I understand that: 我明白那个:
value = (a > b) ? a : b;
is the same as: 是相同的:
if (a > b)
value = a;
else
value = b;
But I'm having trouble deciphering what this means: 但我无法破译这意味着什么:
EDIT (the previous example I used was not good, this is real code from another example): 编辑 (我之前使用的例子并不好,这是另一个例子中的真实代码):
Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(PROPERTY_ID)
: (trackerId == TrackerName.GLOBAL_TRACKER) ? analytics.newTracker(R.xml.global_tracker)
: analytics.newTracker(R.xml.ecommerce_tracker);
How do I rewrite the last equation in terms of if
, else if
, and else
? 如何根据if
, else if
和else
重写最后一个等式?
You need a second conditional for this ternary expression to work. 您需要第二个条件才能使此三元表达式起作用。
value = (a > b) ? a : (b > c) ? c : d;
Then it would become: 然后它会变成:
if (a > b) {
value = a;
} else if (b > c) {
value = c;
} else {
value = d;
}
In your case: 在你的情况下:
if (trackerId == TrackerName.APP_TRACKER) {
t = analytics.newTracker(PROPERTY_ID);
} else if (trackerId == TrackerName.GLOBAL_TRACKER) {
t = analytics.newTracker(R.xml.global_tracker);
} else {
t = analytics.newTracker(R.xml.ecommerce_tracker);
}
Resources: 资源:
So based on the example you linked : 所以基于你链接的例子 :
Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(PROPERTY_ID)
: (trackerId == TrackerName.GLOBAL_TRACKER) ? analytics.newTracker(R.xml.global_tracker)
: analytics.newTracker(R.xml.ecommerce_tracker);
Which you seemed to have used to produce value = (a > b) ? a : b ? c : d;
您似乎习惯于产生value = (a > b) ? a : b ? c : d;
value = (a > b) ? a : b ? c : d;
, which should probably be more like, value = (a == b) ? c : (a == d) ? e : f
,应该更像是, value = (a == b) ? c : (a == d) ? e : f
value = (a == b) ? c : (a == d) ? e : f
value = (a == b) ? c : (a == d) ? e : f
, it would read something like... value = (a == b) ? c : (a == d) ? e : f
,它会读到像......
Tracker t = null;
if (trackerId == TrackerName.APP_TRACKER) {
t = analytics.newTracker(PROPERTY_ID);
} else if ((trackerId == TrackerName.GLOBAL_TRACKER)) {
t = analytics.newTracker(R.xml.global_tracker);
} else {
t = analytics.newTracker(R.xml.ecommerce_tracker);
}
Use an IDE like Eclipse that offers the possibility to automatically rewrite ternary operators as ifs. 使用像Eclipse这样的IDE,它可以像ifs一样自动重写三元运算符。 Ctrl + 1
opens the quick fix shown below. Ctrl + 1
打开下面显示的快速修复程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.