相关疑难解决方法(0)

何时使用mixin以及何时在Dart中使用接口?

我非常熟悉接口和抽象类的概念,但不熟悉mixins的概念.

现在,在Dart中,每个类都A定义了一个隐式接口,可以B通过使用implements关键字由另一个类实现.没有明确的方式来声明接口,例如,在Java中,接口只包含未实现的方法(最终是静态变量).在Dart中,由于接口是由类定义的,接口的方法A实际上可能已经实现,但实现的类B仍然需要覆盖这些实现.

我们可以从以下代码中看到这种情况:

class A {
  void m() {
    print("method m");
  }
}

// LINTER ERROR: Missing concrete implementation of A.m
// Try implementing missing method or make B abstract.
class B implements A {
}
Run Code Online (Sandbox Code Playgroud)

在Dart中,mixin也是通过普通的类声明来定义的......

...原则上,每个类都定义了一个可以从中提取的mixin.但是,在此提议中,mixin只能从没有声明构造函数的类中提取.这种限制避免了由于需要在继承链上传递构造函数参数而引起的复杂化.

mixin基本上是一个可以定义未实现或实现的方法的类.这是一种将方法添加到另一个类而无需逻辑上使用继承的方法.在Dart中,mixin应用于超类,通过"正常"继承扩展,如下例所示:

class A {
  void m() {
    print("method m");
  }
}

class MyMixin {
  void f(){
    print("method f");
  }
}

class B extends A with MyMixin {
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我们应该注意到,B …

oop abstract-class interface mixins dart

37
推荐指数
5
解决办法
7385
查看次数

标签 统计

abstract-class ×1

dart ×1

interface ×1

mixins ×1

oop ×1