簡體   English   中英

如何在 dart 中創建多個構造函數?

[英]How can I create multiple constructors in dart?

我想通過調用具有不同數量參數的構造函數來創建不同的對象。 我怎樣才能在 Dart 中實現這一目標?

class A{
  String b,c,d;

  A(this.b,this.c)
  A(this.b,this.c,this.d)

}

參見Tour of Dart 的構造函數部分

基本上 Dart 不支持方法/構造函數重載。 但是 Dart 允許命名構造函數和可選參數。

在您的情況下,您可以:

class A{
  String b,c,d;

  /// with d optional
  A(this.b, this.c, [this.d]);

  /// named constructor with only b and c
  A.c1(this.b, this.c);
  /// named constructor with b c and d
  A.c2(this.b, this.c, this.d);
}

為清楚起見,您可以使用命名構造函數來為一個類實現多個構造函數。

class A{
      String b,c,d;

      // A(); //default constructor no need to write it
      A(this.b,this.c); //constructor #1
    
      A.namedConstructor(this.b,this.c,this.d); //another constructor #2
    
    }

您可以使用工廠構造函數

class A{
  String b,c,d;

  A(this.b,this.c,this.d)
  
  factory A.fromBC(String b, String c) => A(b, c, "");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM