简体   繁体   English

class和dart中的mixin有什么区别?

[英]What is the difference between class and mixin in dart?

What is the difference between:有什么区别:

class A {}

class B with A{}

and

mixin A{}

class B with A{}

?

In Dart, a class can only extend one other class. But it can implement or mixin as many as you want.在 Dart 中,一个 class 只能extend另一个 class。但它可以implementmixin任意多个。 The thing is, when you extend a class, you inherit all its attributes, methods and it's constructors.问题是,当您扩展 class 时,您继承了它的所有属性、方法和构造函数。 When you implement a class, if you are adding only methods/attributes that you don't already have, you can simply continue your code.当您实现 class 时,如果您只添加您还没有的方法/属性,您可以简单地继续您的代码。 If you are implementing an abstract method, you'll need to actually implement it.如果要实现抽象方法,则需要实际实现它。 Now, mixins are like extended classes, the classes that mix them, are their child as well as with extend and implements, but it has no constructor.现在,mixins 就像扩展类,混合它们的类是它们的子类,也有 extend 和 implements,但它没有构造函数。

The actual idea for mixins is that you can add functionalities to any class, and they don't have to extend another class. That's why they usually do simple stuff only. mixins 的实际想法是,您可以向任何 class 添加功能,而他们不必扩展另一个 class。这就是为什么他们通常只做简单的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM