特殊操作符
1. as,is,is!
as 类型转换
(emp as Person).firstName = 'Bob';
复制代码
is 类型判断
if (emp is Person) {
// Type check
emp.firstName = 'Bob';
}
复制代码
2. 赋值操作符 ??=
b值为null,则赋值为value
// Assign value to b if b is null; otherwise, b stays the same
b ??= value;
复制代码
3. 条件运算符
condition为true,则值为expr1;否则为expr2
condition ? expr1 : expr2
var visibility = isPublic ? 'public' : 'private';
复制代码
expr1不为空,则值为expr1;否则为expr2
expr1 ?? expr2
String playerName(String name) => name ?? 'Guest';
复制代码
4. switch-case
case 后有操作语句,而无break报错
var command = 'OPEN';
switch (command) {
case 'OPEN':
executeOpen();
// ERROR: Missing break
case 'CLOSED':
executeClosed();
break;
}
复制代码
case后无操作语句,可缺少break
var command = 'CLOSED';
switch (command) {
case 'CLOSED': // Empty case falls through.
case 'NOW_CLOSED':
// Runs for both CLOSED and NOW_CLOSED.
executeNowClosed();
break;
}
复制代码
case后有操作语句,希望继承执行,可使用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;
}
复制代码