如何在Dart中创建静态扩展方法? [英] How to create a static extension method in Dart?

查看:72
本文介绍了如何在Dart中创建静态扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建静态 扩展方法在我的一个类中(它是自动生成的,因此我不能轻易对其进行修改).根据文档,这应该是可能的:

I'm trying to create a static extension method on one of my classes (which is autogenerated, so I can't easily modify it). According to the docs, this should be possible:

扩展也可以具有静态字段和静态帮助器方法.

Extensions can also have static fields and static helper methods.

即使这个小例子也不能编译:

Yet even this small example does not compile:

extension Foo on String {
  static String foo() => 'foo!';
}

void main() {
  print(String.foo());
}

Error: Method not found: 'String.foo'.
  print(String.foo());
               ^^^

我在做什么错了?

推荐答案

文档意味着扩展类自身可以具有 static 字段和辅助方法.这些不会是扩展类的扩展.也就是说,在您的示例中, Foo.foo()是合法的,而 String.foo()则不是.

The docs mean that the extension classes themselves can have static fields and helper methods. These won't be extensions on the extended class. That is, in your example, Foo.foo() is legal but String.foo() is not.

您当前无法创建静态的扩展方法.参见 https://github.com/dart-lang/language/issues/723.

You currently cannot create extension methods that are static. See https://github.com/dart-lang/language/issues/723.

请注意,您可能还会看到称为静态扩展方法"的Dart扩展方法,但是那里的静态"意味着扩展是静态应用的(即,基于编译时已知的对象类型,而不是其运行时)类型).

Note that you also might see Dart extension methods referred to as "static extension methods", but "static" there means that the extensions are applied statically (i.e., based on the object's type known at compilation-time, not its runtime type).

这篇关于如何在Dart中创建静态扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆