如何在dart中创建多个构造函数? [英] How can I create multiple constructors in dart?

查看:53
本文介绍了如何在dart中创建多个构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to create different objects by calling constructors that have different number of parameters. How can I achieve this in Dart?

class A{
  String b,c,d;

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

}

推荐答案

请参见"飞镖之旅 .

基本上,Dart不支持方法/构造函数重载.但是Dart允许命名构造函数和可选参数.

Basically Dart doesn't support methods/constructor overloading. However Dart allows named constructors and optional parameters.

在您的情况下,您可以:

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

这篇关于如何在dart中创建多个构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆