我试图了解开关在飞镖中是如何工作的.我有非常简单的代码:
methodname(num radians) {
switch (radians) {
case 0:
// do something
break;
case PI:
// do something else
break;
}
}
Run Code Online (Sandbox Code Playgroud)
遗憾的是,这不起作用.如果保留为此错误是:case表达式必须具有相同的类型(我的类型是num,但不是编辑器).如果我将0更改为0.0则表示:切换类型表达式double不能覆盖==运算符 - 我不知道这意味着什么!
那么切换案例的方法是什么?我可以将它转换为if/else可能但我想知道如何使开关工作,为什么它不起作用.
我正在运行最新的DartEditor稳定版本.
请有人可以帮忙吗?
Gün*_*uer 13
使用'=='比较双值不是很可靠,应该避免(不仅在Dart中,而且在大多数语言中).
你可以做点什么
methodname(num radians) {
// you can adjust this values according to your accuracy requirements
const myPI = 3142;
int r = (radians * 1000).round();
switch (r) {
case 0:
// do something
break;
case myPI:
// do something else
break;
}
}
Run Code Online (Sandbox Code Playgroud)
此问题包含您可能感兴趣的一些其他信息
更多信息:
小智 11
这是 Dart 中 switch case 的示例。
问:编写一个程序来打印给定数字的乘法表。接受用户的输入并显示其乘法表
import 'dart:io';
void main(List<String> args) {
print('enter a number from 1 to 7');
var input = stdin.readLineSync();
int day = int.parse(input!);
switch (day) {
case 1:
print('Sunday');
break;
case 2:
print('Monday');
break;
case 3:
print('Tuesday');
break;
case 4:
print('Wednesday');
break;
case 5:
print('Thursday');
break;
case 6:
print('Friday');
break;
case 7:
print('Saturday');
break;
default:
print(' invalid entry');
}
}
Run Code Online (Sandbox Code Playgroud)
Dart 中的 Switch 语句使用==. 被比较的对象必须都是同一个类(而不是其任何子类型)的实例,并且该类不能覆盖==。枚举类型在switch语句中运行良好。
case通常,每个非空子句都以 break 语句结尾。结束非空case子句的其他有效方法是 a continue, throw, orreturn语句。
default当没有 case 子句匹配时,使用子句执行代码:
var command = 'OPEN';
switch (command) {
case 'CLOSED':
executeClosed();
break;
case 'PENDING':
executePending();
break;
case 'APPROVED':
executeApproved();
break;
case 'DENIED':
executeDenied();
break;
case 'OPEN':
executeOpen();
break;
default:
executeUnknown();
}
Run Code Online (Sandbox Code Playgroud)
以下示例省略break了case子句中的语句,从而产生了错误:
var command = 'OPEN';
switch (command) {
case 'OPEN':
executeOpen();
// ERROR: Missing break
case 'CLOSED':
executeClosed();
break;
}
Run Code Online (Sandbox Code Playgroud)
然而,Dart 确实支持空case子句,允许一种形式的失败:
var command = 'CLOSED';
switch (command) {
case 'CLOSED': // Empty case falls through.
case 'NOW_CLOSED':
// Runs for both CLOSED and NOW_CLOSED.
executeNowClosed();
break;
}
Run Code Online (Sandbox Code Playgroud)
如果你真的想要失败,你可以使用一个continue语句和一个标签:
var command = 'CLOSED';
switch (command) {
case 'CLOSED':
executeClosed();
continue nowClosed;
// Continues executing at the nowClosed label.
nowClosed:
case 'NOW_CLOSED':
// Runs for both CLOSED and NOW_CLOSED.
executeNowClosed();
break;
}
Run Code Online (Sandbox Code Playgroud)
一个case子句可以有局部变量,这些变量只在该子句的作用域内可见。
参考:https : //dart.dev/guides/language/language-tour#switch-and-case
我认为 Dart 3 的switch 表达式为此提供了更简洁的语法。
bool methodname(num radians) {
const myPI = 3142;
int r = (radians * 1000).round();
return switch (r) {
myPI => true,
_ => false,
};
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17203 次 |
| 最近记录: |