Dart中的"with"关键字

rom*_*nos 20 dart

有人可以在Dart中写一些关键字的正式定义吗?

在官方的Dart示例中,我只发现:

class TaskElement extends LIElement with Polymer, Observable {
Run Code Online (Sandbox Code Playgroud)

但我仍然无法理解它到底在做什么.

Jac*_*son 39

with关键字指示使用"混入"的.看到这里.

mixin是指能够将另一个或多个类的功能添加到您自己的类中,而无需继承这些类.现在可以在类上调用这些类的方法,并执行这些类中的代码.Dart没有多重继承,但使用mixins允许您折叠其他类以实现代码重用,同时避免多重继承会导致的问题.

我注意到您已经回答了一些关于Java的问题 - 在Java术语中,您可以将mixin视为一个接口,它不仅可以指定给定的类将包含给定的方法,还可以为该方法提供代码.

  • 这是对“mixin”最好的解释之一!谢谢! (2认同)

Yog*_*ngh 12

您可以将 mixin 视为 Java 中的接口,也可以将其视为 Swift 中的协议。这是一个简单的示例。

mixin Human {
  String name;
  int age;

  void about();
}

class Doctor with Human {
  String specialization;
  Doctor(String doctorName, int doctorAge, String specialization) {
    name = doctorName;
    age = doctorAge;
    this.specialization = specialization;
  }

  void about() {
    print('$name is $age years old. He is $specialization specialist.');
  }
}


void main() {
  Doctor doctor = Doctor("Harish Chandra", 54, 'child');
  print(doctor.name);
  print(doctor.age);
  doctor.about();
}
Run Code Online (Sandbox Code Playgroud)

希望对理解有所帮助。