【问题标题】:What's the rationale behind not inheriting static variables, in Dart?在 Dart 中不继承静态变量的原因是什么?
【发布时间】:2013-11-26 11:26:51
【问题描述】:

Dart 中,如果一个类扩展另一个类,则扩展类继承所有超类非静态变量,但不继承任何静态变量。

例如

class TestUpper {
  static final String up = 'super';
  String upup = 10;
}

class TestLower extends TestUpper {
  static final String low = 'lower';
  String lowlow = 11;
} 

var lower = new TestLower();
print( lower.lowlow );  // <== 11
print( lower.upup );    // <== 10
print( TestLower.low ); // <== "lower"
print( TestLower.up );  // <== No static getter 'get:up' declared in class 'TestLower'

这是正常行为吗?如果是这样,如果有人解释其背后的理由,我将不胜感激。

【问题讨论】:

    标签: class types static dart


    【解决方案1】:

    是的,静态成员没有继承。见Static Methods section of the language specification

    静态方法的继承在 Dart 中几乎没有用处。静态方法不能被覆盖。任何需要的静态函数都可以从其声明库中获取,无需通过继承将其引入作用域。经验表明,开发人员对继承方法不是实例方法的想法感到困惑。

    当然,静态方法的整个概念是值得商榷的,但在这里保留它是因为很多程序员都熟悉它。 Dart 静态方法可以看作是封闭库的函数。

    【讨论】:

    • 我明白其中的道理,但不同意。如果您要在扩展类中公开超类,则应该公开超类。在没有反射的情况下工作时,我可以看到没有必要的地方 - 只需查看代码! - 但是当一般地使用类时,非继承是一个真正的痛苦。
    • 欢迎在Dart-misc group 上发表您的反馈意见。
    • 给出出处的好答案!
    猜你喜欢
    • 2012-04-11
    • 2016-09-10
    • 2020-10-18
    • 2011-04-24
    • 2017-02-07
    • 2011-03-29
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    相关资源
    最近更新 更多