【问题标题】:Is there a way to add a static extension method on a class directly in Dart?有没有办法直接在 Dart 中的类上添加静态扩展方法?
【发布时间】:2020-01-13 22:39:59
【问题描述】:

我在comment 中读到关于 C# 的一个类似问题,即只能从实例调用扩展方法。 Dart 也一样吗?我正在尝试向 Platform class 添加一个吸气剂,它将像这样调用。 Platform.isDesktop。但是,这仅在调用类的实例时有效,即Platform().isDesktop,即使将实例方法声明为静态也是如此。为什么不能添加静态成员?

代码:

extension on Platform {
  bool get isMobile => Platform.isAndroid || Platform.isIOS;
  bool get isDesktop => Platform.isWindows || Platform.isMacOS || Platform.isLinux;
}

【问题讨论】:

    标签: dart extension-methods


    【解决方案1】:

    是的,Dart 也是如此。扩展方法的作用类似于实例方法,而不是静态方法。目前没有办法从类外给类添加静态方法。

    您可以在扩展中声明静态方法,但它们在扩展本身上是静态的(您可以使用ExtensionName.methodName() 调用它们)。

    https://github.com/dart-lang/language/issues/723中有关于添加扩展静态方法的讨论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      • 1970-01-01
      • 2020-04-09
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      相关资源
      最近更新 更多