代码之家  ›  专栏  ›  技术社区  ›  Nico Rodsevich

如何在DART中使用复杂参数super()调用?

  •  3
  • Nico Rodsevich  · 技术社区  · 8 年前

    根据我的研究,在dart中,必须在构造函数的函数体之外调用super。

    假设这种情况:

    /// Unmodifiable given class
    class Figure{
      final int sides;
      const Figure(this.sides);
    }
    
    /// Own class
    class Shape extends Figure{
      Shape(Form form){
        if(form is Square) super(4);
        else if(form is Triangle) super(3);
      }
    }
    

    这会抛出分析错误(超类没有0个参数构造函数,表达式super(3)没有对函数求值,因此无法调用)。如何实现示例的指定功能?

    1 回复  |  直到 8 年前
        1
  •  4
  •   tenhobi    8 年前

    在DART中调用超级构造函数 初始化列表 使用。

    class Shape extends Figure{
      Shape(Form form) : super(form is Square ? 4 : form is Triangle ? 3 : null);
    }
    

    如果需要执行语句,可以添加一个工厂构造函数,该构造函数转发给(私有的)常规构造函数,如

    class Shape extends Figure{
    
      factory Shape(Form form) {
        if (form is Square) return new Shape._(4);
        else if(form is Triangle) return new Shape._(3);
      }
      Shape._(int sides) : super(sides)
    }