dart - 方法和类

57 阅读1分钟

方法

  • 自定义方法
    • 类型 方法名(参数) {方法体}
    • 可选参数用[]进行包裹
    int intFn() {
      return 11;
    }
    // 带有可选参数的函数
    String kxcs( String name, [int? age]) {
      if(age != null) {
        return '名字$name年龄$age';
      } else {
        return '年龄保密';
      }
    }
    void main () {
      int a = intFn();
      print(a); // 11
      String b = kxcs('lyx', 25);
      String c = kxcs('lyf');
      print(b); // 名字lyx年龄25
      print(c); // 年龄保密
    }
    

  • 大部分的和js es6类似
  • dart中没有访问修饰符, 可以用_属性或方法名来将一个属性或方法定义成一个私有的属性或方法
  • dart中的对象运算符
    • ?: 条件运算符, 检测 ?. 前面的变量是否存在, 类似ts中的 obj?.name
    • as: 类型断言 同 ts中的 str as string
    • is: 类型判断, a is int, 判断a是不是int类型
    • ..: 级联操作符,可以连续的更改对象内容或调用对象内方法
    // 引入类文件
     import './pubilcClass/animal.dart';
     class Ract {
       int _height = 0;
       int _weight = 0;
       String name = '';
       int age = 0;
       Ract(height, weight) {
         this._height = height;
         this._weight = weight;
       }
       int jsRact() {
         return this._height * this._weight;
       }
       printNam() {
         print('名字${this.name}, 年龄: ${this.age}');
       }
     }
     void main() {
       var a1 = new Animal(); // 我是私有属性
       a1.setAnimalName('王八'); //我是一个王八
       Ract ra = new Ract(3, 4);
       int mj = ra.jsRact();
       print(mj); //12
       // 级联运算符, ..
       ra..name = '张三'
         ..age= 25
         ..printNam();// 名字张三, 年龄: 25
     }
    
  • 子类继承父类方法, 改写父类方法时, 建议在修改的上方加一个@override, 来代表复写方法