【问题标题】:In Dart I'm trying to extend a class while changing the TYPE of one of its properties在 Dart 中,我试图扩展一个类,同时改变它的一个属性的类型
【发布时间】:2020-09-08 18:58:22
【问题描述】:

Class1 有一个属性List<ClassA> xyz = [];。 ClassA 有许多属性和方法。 ClassB 扩展了 ClassA,添加了额外的属性和方法。有没有办法让我创建扩展 Class1 的 Class2 但将 xyz 的类型更改为List<ClassB>?如果这令人困惑,希望下面的代码将举例说明我正在尝试完成的工作。基本上与重写方法但重写属性相同。

class Game {
  int points;
  String opponent;
  int opponentPoints;
}

class FootballGame extends Game {
  int touchdowns;
  int opponentstouchdowns;
}

class BaseballGame extends Game {
  int homeruns;
  int opponentsHomeruns;
}

class Team {
   String name;
   List<Game> games;

  double winningPercentage() {
    int wins = 0;
    for(var game in games){
      wins += (game.points > game.opponentPoints) ? 1 : 0;        
    }
    return wins / games.length;
  }
}

class FootballTeam extends Team {
  // How do I change the TYPE of the games property to <FootballGame>

}

【问题讨论】:

    标签: class flutter dart extends


    【解决方案1】:

    在这种情况下,您可以使用covariant keyword

    class FootballTeam extends Team {
      @override
      covariant List<FootballGame> games;
    }
    

    但是,请注意这样做可能不安全;您需要covariant 关键字的原因是为了抑制出现的类型错误,因为覆盖可能违反基类的约定:基类宣传games 可以分配List&lt;Game&gt;,但是这样的分配对于派生类无效。通过使用covariant 关键字,您可以禁用类型检查并负责确保您在实践中不违反合同。

    请注意,如果games 成员是final(或只是一个getter),那么覆盖(使用更具体的类型)将是安全的,不需要使用covariant

    编辑

    我忘记了我在写a more detailed answer 时写了这个答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-07
      • 1970-01-01
      • 2019-08-05
      • 2012-08-28
      • 2020-10-26
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      相关资源
      最近更新 更多