Dart 语法基础篇

本文深入探讨了Dart语言的重载运算符功能,演示了如何通过重载运算符如+来自定义类的行为,例如Person类的年龄相加。同时介绍了Dart的多继承特性with关键字,展示了如何在一个类中实现多个接口的方法。此外,文章还讲解了Dart的导入优化技巧,以及级联语法和断言的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

operator(重载符)

class Person {
  var age;
  Person(var age) {
    this.age = age;
  }
  ### 重载可以自定义==,-等等
  operator +(p) => new Person(age + p.age);
}

main() {
  Person p = new Person(10);
  Person p2 = new Person(20);
  print((p + p2).age);
}

//print(30)

with(多继承)

class a {
  eat() {
    print("111");
  }
}

class b {
  eat2() {
    print("222");
  }
}

class c with a, b {}

main() {
  new c().eat();
  new c().eat2();
}

导入优化

import 'package:stack1.dart' as stack1;
import 'package:stack2.dart' as stack2;

------------------------
import 'stack1.dart' show pop,push;
import 'stack2.dart' hide pop,push;
---------------------------
import 'stack1.dart' as stack1 show pop,push
-----------------
##延迟导入
import ‘xxx.dart’ deferred as xxx;

导出

export 'xxx.dart' show xxxx;

级联

"Hello".length.toString();//值为5
"Hello"..length.toString();//值为Hello

变种

var address=new Address.of("xxx)";
address.set(“xxxx”);
address.state="xxx";
new Address.of("xxx")
..set("xxx")
..state=“xxxx”

assert

factorial(int x){
 return x==0?1:x*factorial(x-1);
}
如果传入-1就死循环
factorial(int x){
 assert(x>=0);
 return x==0?1:x*factorial(x-1);
}

等同于
factorial(int x){
 if(x<0)throw new AssertionError();
 return x==0?1:x*factorial(x-1);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值