简体   繁体   English

相当于 Swift “扩展”的 dart 是什么?

[英]What is the dart equivalent to Swift “extensions”?

Keyword/reserved word extension allow code to be much cleaner by using an existing class in the standard frameworks without subclassing them.关键字/保留字extension通过使用标准框架中的现有类而无需对它们进行子类化,从而使代码更加简洁。 Is there a keyword in Dart that allows the same behavior? Dart 中是否有允许相同行为的关键字?

extension Double {
    var mm: Double { return self / 1_000.0 }
}

let oneInch = 25.4.mm
print("One inch is \(oneInch) meters")

They are finally here 🥳他们终于来了🥳

From dart version 2.6 (not 100% sure).从 dart 2.6 版开始(不是 100% 确定)。

class Foo {
  printFoo()  {
    print("Foo");
  }
}

extension Bar on Foo { 
  printBar()  {
    print("Bar");
  }
}

void main() {
  final foo = Foo();
  foo.printFoo();
  foo.printBar();
}

prints:印刷:

Foo

Bar酒吧

You can give it a try in dart pad.你可以试试飞镖垫。

TL;DR: Sadly, Dart doesn't support extension methods. TL;DR:遗憾的是,Dart 不支持扩展方法。

In the Dart repository, there's an issue about how to add new functionality to existing types for that.在 Dart 存储库中,存在一个关于如何为此向现有类型添加新功能问题 More specifically, there are issues for extension methods and extension types .更具体地说,扩展方法扩展类型存在问题。

Of course, you can always use new class es that extend existing classes introduce new functionality on top of them.当然,你总是可以使用新的classextend现有的类,在它们之上引入新的功能。 However, that only works for non-primitive classes, so let's hope for the best.然而,这只适用于非原始类,所以让我们希望最好。 Your best shot probably is to upvote the issues linked above.您最好的选择可能是对上面链接的问题进行投票。

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

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