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

2023-11-21

我想通过调用具有不同数量参数的构造函数来创建不同的对象。我怎样才能在 Dart 中实现这一目标?

class A{
  String b,c,d;

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

}

See 构造函数部分飞镖之旅.

基本上 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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 dart 中创建多个构造函数? 的相关文章