在Dart中切换失败 [英] Switch fallthrough in Dart
问题描述
我从今天开始学习Dart,遇到了一些我的Google技能很难找到的东西。
I started learning Dart today, and I've come across something that my google skills are having trouble finding.
我怎么会陷入困境非空的情况?
How do I have a fall-through in a non-empty case?
我的用例是这样的:我正在编写sprintf实现(因为dart也没有此实现),除此以外它都可以工作跌倒的东西。解析变量类型时,例如,可以使用%x和%X,其中大写类型告诉格式化程序输出应该是大写的。
My use case is this: I'm writing a sprintf implementation (since dart doesn't have this too), which would work except for this fall-through thing. When parsing the variable type you can, for example, have "%x" versus "%X" where the upper case type tells the formatter that the output is supposed to be uppercase.
半伪代码如下:
bool is_upper = false;
switch (getType()) {
case 'X':
is_upper = true;
case 'x':
return formatHex(is_upper);
}
我可以想到的另一种方法是,以下一种方法
The other ways I can think of doing this, would one of the following
1:
switch (getType()) {
case 'X': case 'x':
return formatHex('X' == getType());
}
2:
var type = getType();
if (type in ['x', 'X']) {
return formatHex('X' == getType());
}
现在,第二种选择看起来不错,但是您必须记住有11种情况,这意味着要有11个 if(在[]中键入)
,这是我想要的更多类型。
Now, the second choice almost looks good, but then you have to remember that there are eleven cases, which would mean having eleven if (type in [])
, which is more typing that I'd like.
所以,飞镖有一些我不知道的 /// $ FALL-THROUGH $
吗?
So, does dart have some // //$FALL-THROUGH$
that I don't know about?
谢谢。
推荐答案
Dart规范为开关盒提供了一种继续使用另一个开关盒的方式使用继续:
The Dart specification gives a way for a switch case to continue to another switch case using "continue":
switch (x) {
case 42: print("hello");
continue world;
case 37: print("goodbye");
break;
world: // This is a label on the switch case.
case 87: print("world");
}
它可在VM中使用,但可惜的是dart2js开关的实现尚未实现支持该功能。
It works in the VM, but sadly the dart2js switch implementation doesn't yet support that feature.
这篇关于在Dart中切换失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!