Dart:二十二、混入

2025-05-22  本文已影响0人  DB001

混入

混入 with

class Phone {
  void call() {
    print('Phone is calling...');
  }
}

class Android {
  void playStore() {
    print('Google play store');
  }
}

class Ios {
  void appleStore() {
    print('Apply store');
  }
}
class Xiaomi with Phone, Android, Ios {}

采用 with ... , .... , ... 方式 mixin 入多个类功能

void main(List<String> args) {
  var p = Xiaomi();
  p.call();
  p.playStore();
  p.appleStore();
}

Phone is calling...
Google play store
Apply store

函数重名冲突

class Android {
  void playStore() {
    print('Google play store');
  }

  void call() {
    print('Android phone is calling...');
  }
}

class Ios {
  void appleStore() {
    print('Apply store');
  }

  void call() {
    print('Ios phone is calling...');
  }
}
void main(List<String> args) {
  var p = Xiaomi();
  p.call();
  p.playStore();
  p.appleStore();
}

Ios phone is calling...
Google play store
Apply store

可以发现后面的覆盖了前面的内容

mixin 不能构造函数

class Android {
  Android();
  ...
}

The class 'Android' can't be used as a mixin because it declares a constructor.
mixin Android {
  // mixin 中不能定义 constructor
  ...
}

mixin on 限定条件

mixin Android on Phone {
  void playStore() {
    print('Google play store');
  }

  @override
  void call() {
    super.call();
    print('Android phone is calling...');
  }
}

错误

class Xiaomi with Android {}

'Android' can't be mixed onto 'Object' because 'Object' doesn't implement 'Phone'.
Try extending the class 'Android'.

正确

class Xiaomi with Phone,Android {}
上一篇 下一篇

猜你喜欢

热点阅读