可以在 Dart 中的抽象类中声明静态方法吗? [英] Can one declare a static method within an abstract class, in Dart?

查看:31
本文介绍了可以在 Dart 中的抽象类中声明静态方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抽象类中,我希望定义静态方法,但遇到了问题.

In an abstract class, I wish to define static methods, but I'm having problems.

在这个简单的例子中

abstract class Main {
  static String get name;
  bool use( Element el );
}

class Sub extends Main {
  static String get name => 'testme';
  bool use( Element el ) => (el is Element);
}

我收到错误:

方法 'get:name' 预期的函数体 static String get name;

function body expected for method 'get:name' static String get name;

声明中是否有拼写错误,或者静态方法与抽象类不兼容?

Is there a typo in the declaration, or are static methods incompatible with abstract classes?

推荐答案

Dart 不继承派生类的静态方法.所以创建抽象的静态方法(没有实现)是没有意义的.

Dart doesn't inherit static methods to derived classes. So it makes no sense to create abstract static methods (without implementation).

如果你想在 Main 类中使用静态方法,你必须在那里完全定义它并且总是像 Main.name

If you want a static method in class Main you have to fully define it there and always call it like Main.name

== 编辑 ==

我确定我从 Gilad Bracha 那里读到或听到了一些关于它的论点,但现在找不到了.

I'm sure I read or heard some arguments from Gilad Bracha about it but can't find it now.

恕我直言,这种行为在静态类型语言中很常见(我不知道很多动态语言).静态方法就像一个顶级函数,其中类名只是作为一个命名空间.静态方法与实例化对象无关,因此继承不适用.在继承"静态方法的语言中,这只是语法糖.Dart 喜欢在这里更明确,并避免混淆实例方法和静态方法(它们实际上不是方法而只是函数,因为它们不作用于实例).这不是我的主要域,但希望无论如何都有意义;-)

This behaviour is IMHO common mostly in statically typed languages (I don't know many dynamic languages). A static method is like a top level function where the class name just acts as a namespace. A static method has nothing to do with an instantiated object so inheritance is not applicable. In languages where static methods are 'inherited' this is just syntactic sugar. Dart likes to be more explicit here and to avoid confusion between instance methods and static methods (which actually are not methods but just functions because they don't act on an instance). This is not my primary domain, but hopefully may make some sense anyways ;-)

这篇关于可以在 Dart 中的抽象类中声明静态方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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