operator.dart
main() {
//Operators 操作符
/// ---------------------------------后缀操作符 ?.--------------------------------
// 条件成员访问 和 . 类似,但是左边的操作对象不能为 null,例如 foo?.bar 如果 foo 为 null 则返回 null,否则返回 bar 成员
String a;
print(a?.length); //输出 null
/// ---------------------------------取商操作符 ~/--------------------------------
// 被除数 ÷ 除数 = 商 ... 余数,A ~/ B = C,这个C就是商。相当于Java里的 /
print(2 / 3); //输出 0.6666666666666666
print(2 ~/ 3); // 输出 0
/// ---------------------------------类型判定操作符--------------------------------
//类型判定操作符:as、is、is!在运行时判定对象类型
//as 类型转换
num iNum = 1;
num dNum = 1.0;
int i = iNum as int;
double d = dNum as double;
print([i, d]); //输出 [1, 1.0]
// String s = iNum as String;
//is 如果对象是指定的类型返回 True
print(iNum is int); // 输出 true
Child child;
Child child1 = new Child();
print(child is Parent); //child is Null 输出 false
print(child1 is Parent); //输出 true
//is! 如果对象是指定的类型返回 False
print(iNum is! int); //输出 false
/// ---------------------------------条件表达式--------------------------------
// 三目运算符 condition ? expr1 : expr2
bool isFinish = true;
String txtVal = isFinish ? 'yes' : 'no';
// expr1 ?? expr2,如果 expr1 是 non-null,返回其值; 否则执行 expr2 并返回其结果。
bool isPaused;
isPaused = isPaused ?? false;
//或者
isPaused ??= false;
/// ---------------------------------级联操作符--------------------------------
// .. 可以在同一个对象上 连续调用多个函数以及访问成员变量。
// 严格来说, 两个点的级联语法不是一个操作符。 只是一个 Dart 特殊语法。
StringBuffer sb = new StringBuffer();
sb
..write('dongnao')
..write('flutter')
..write('\n')
..writeln('damon');
//重写操作符
}
class Parent {}
class Child extends Parent {}
输出:
D:\flutter\bin\cache\dart-sdk\bin\dart.exe --enable-asserts --enable-vm-service:15442 D:\Code\Flutter\FlutterHello\flutter_app\lib\operator.dart
lib/operator.dart: Warning: Interpreting this as package URI, 'package:flutterapp/operator.dart'.
Observatory listening on http://127.0.0.1:15443/SyXym9TCePM=/
null
0.6666666666666666
0
[1, 1.0]
true
false
true
false
Process finished with exit code 0
本文深入探讨Dart语言中的各种操作符,包括条件成员访问操作符?.、取商操作符~/、类型判定操作符as/is/is!、条件表达式以及级联操作符..。通过实例演示了每个操作符的使用方法和作用,为Dart开发者提供了全面的理解和实践指导。
459

被折叠的 条评论
为什么被折叠?



