简体   繁体   English

如何在 dart 中创建多个构造函数?

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

I would like to create different objects by calling constructors that have different number of parameters.我想通过调用具有不同数量参数的构造函数来创建不同的对象。 How can I achieve this in Dart?我怎样才能在 Dart 中实现这一目标?

class A{
  String b,c,d;

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

}

See Constructor section of Tour of Dart .参见Tour of Dart 的构造函数部分

Basically Dart doesn't support methods/constructor overloading.基本上 Dart 不支持方法/构造函数重载。 However Dart allows named constructors and optional parameters.但是 Dart 允许命名构造函数和可选参数。

In your case you could have:在您的情况下,您可以:

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);
}

You can use the named constructor for clarity to implement multiple constructors for a class.为清楚起见,您可以使用命名构造函数来为一个类实现多个构造函数。

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
    
    }

You can use factory constructors您可以使用工厂构造函数

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