Dart絕大多數(shù)的操作符和其他語(yǔ)言很相似绰筛,先列一張表
image.png
image.png
下面說(shuō)一些不常見(jiàn)的
- as 強(qiáng)轉(zhuǎn)操作符
(emp as Person).firstName = 'Bob';
- is / is! 判斷對(duì)象類(lèi)型操作符
if (emp is Person) {
// Type check
emp.firstName = 'Bob';
}else if(emp is! Person){
.....
}
- 空賦值操作符
b ??= value; //當(dāng)b為空的時(shí)候枢泰,value的值才會(huì)賦值給b
?. 類(lèi)似于Kotlin的非空判斷,a?.b 在a不為空的時(shí)候執(zhí)行a.b
for in循環(huán)铝噩,除了常規(guī)的for循環(huán)以外衡蚂,還支持for in 循環(huán)
var collection = [0, 1, 2];
for (var x in collection) {
print(x); // 0 1 2
}
- Switch case 除了正常的比較也是支持枚舉類(lèi)型的
var command = 'OPEN';
switch (command) {
case 'OPEN':
executeOpen();
// ERROR: Missing break
case 'CLOSED':
executeClosed();
break;
}
還有一種用法是在進(jìn)入一個(gè)case之后根據(jù)判斷如果true我要執(zhí)行A case 如果是false我要執(zhí)行 B case,Dart也提供了支持骏庸,利用continue關(guān)鍵字加上自定義的標(biāo)簽來(lái)完成
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;
}
斷言
Dart里面支持?jǐn)嘌悦祝惚仨毚_保判斷是正確的才能通過(guò)這個(gè)斷言,斷言在生產(chǎn)環(huán)境中不起作用
// Make sure the variable has a non-null value.
assert(text != null);
// Make sure the value is less than 100.
assert(number < 100);
// Make sure this is an https URL.
assert(urlString.startsWith('https'));
異常
throw Exception
void distanceTo(Point other) => throw UnimplementedError();//這是拋出異常的方法catch
try {
breedMoreLlamas();
} on OutOfLlamasException {
// A specific exception
buyMoreLlamas();
} on Exception catch (e) {
// Anything else that is an exception
print('Unknown exception: $e');
} catch (e) {
// No specified type, handles all
print('Something really unknown: $e');
}
on和catch的區(qū)別應(yīng)該在于是否關(guān)心異常的實(shí)例
- 捕獲堆棧信息
try {
// ···
} on Exception catch (e) {
print('Exception details:\n $e');
} catch (e, s) {
print('Exception details:\n $e');
print('Stack trace:\n $s');
}
你可以在catch里面多增加一個(gè)參數(shù)具被,第一個(gè)是異常的實(shí)例玻募,第二個(gè)則是錯(cuò)誤的堆棧信息
- rethrow
Dart允許你在捕獲異常的同時(shí)進(jìn)行傳播,如果你需要這樣做一姿,請(qǐng)使用rethrow關(guān)鍵字
void misbehave() {
try {
dynamic foo = true;
print(foo++); // Runtime error
} catch (e) {
print('misbehave() partially handled ${e.runtimeType}.');
rethrow; // Allow callers to see the exception.
}
}
void main() {
try {
misbehave();
} catch (e) {
print('main() finished handling ${e.runtimeType}.');
}
}
By the way .Dart does support "Finally" keyWord too.