zl程序教程

您现在的位置是:首页 >  其他

当前栏目

can‘t be used as a mixin because it extends a class other than ‘Object‘.

IT object be Class can as than used
2023-09-11 14:14:53 时间

程序员如果敲一会就停半天,抱着一杯茶,表情拧巴,那才是在编程

Flutter 项目开发指导 从基础入门到精通使用目录


前言 - 基础关键字

  • class:声明一个类,提供具体的成员变量和方法实现。
  • abstract class:声明一个抽象类,抽象类将无法被实例化。抽象类常用于声明接口方法、有时也会有具体的方法实现。
  • mixin:声明一个Mixin类,与抽象类一样无法被实例化,是一种在多重继承中复用某个类中代码的方法模式,可以声明接口方法或有具体的方法实现。
  • extends:继承,和其它语言的继承没什么区别。
  • with:使用Mixin模式混入一个或者多个Mixin类。
  • implements:实现一个或多个接口并实现每个接口定义的API。
  • on:限制Mixin的使用范围。

1 错误信息

Error: The class ‘B’ can’t be used as a mixin because it extends a class other than ‘Object’.
class C extends A with B{
^
Error: Compilation failed.

在这里插入图片描述

2 测试核心代码

测试使用工具 dartPad

https://dartpad.dartlang.org/flutter

class A {
  void run(){
    print("a run");
  }
}

class B extends A{
  void run(){
    print("b run");
  }
}

class C extends A with B{
  
}
void main() {
  C c = C();
  c.run();
}

3 Dart with 关键字

关键字with表示使用了"Mixin"
mixin指的是将另一个或多个类的功能添加到您自己的类中,而不从这些类继承的能力.这些类的方法现在可以在类上调用,这些类中的代码将被执行.

Dart没有多重继承,但mixin的使用允许您在其他类中折叠以实现代码重用,同时避免多重继承可能导致的问题.
如下定义两个类A、B,分别有自己的方法,A与B分别是抽象的,不可直接创建实例:

abstract class A {
  void run() {
    print("a run");
  }
  void show(){
  }
}

abstract class B {
  void run() {
    print("b run");
  }

  void eat() {
    print("b eat");
  }
}

再定义类C,要求C具备A与B的能力,可以定义如下:

class C extends A with B {
  
}

如果要使 B 再具备 A的能力:

abstract class A {
  void run() {
    print("a run");
  }
  void show(){
  }
}

abstract class B extends A{
  void run() {
    print("b run");
  }

  void eat() {
    print("b eat");
  }
}

如果B再继承A,那么上述定义的类C就会出现异常

Error: The class ‘B’ can’t be used as a mixin because it extends a class other than ‘Object’.
class C extends A with B{

正确的做法:

abstract class A {
  void run() {
    print("a run");
  }

  void show() {
    print("a show");
  }
}

mixin B on A {
  void run() {
    print("b run");
  }

  void eat() {
    print("b eat");
  }
}

class C extends A with B {}

void main() {
  C c = C();
  c.run();
  c.eat();
}