Dart多个构造函数 [英] Dart Multiple Constructors

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

问题描述

真的不可能为dart中的一个类创建多个构造函数吗?

Is it really not possible to create multiple constructors for a class in dart?

在我的Player类中,如果我有这个构造函数

in my Player Class, If I have this constructor

Player(String name, int color) {
    this._color = color;
    this._name = name;
}

然后我尝试添加此构造函数:

Then I try to add this constructor:

Player(Player another) {
    this._color = another.getColor();
    this._name = another.getName();
}

我收到以下错误:


已经定义了默认构造函数。

The default constructor is already defined.

我不是在寻找解决方法通过创建带有一堆非必需参数的构造函数。

I'm not looking for a workaround by creating one Constructor with a bunch of non required arguments.

有解决这个问题的好方法吗?

Is there a nice way to solve this?

推荐答案

您只能有一个未命名 构造函数,但是您可以具有任意数量的其他 命名构造函数

You can only have one unnamed constructor, but you can have any number of additional named constructors

class Player {
  Player(String name, int color) {
    this._color = color;
    this._name = name;
  }

  Player.fromPlayer(Player another) {
    this._color = another.getColor();
    this._name = another.getName();
  }  
}

new Player.fromPlayer(playerOne);

此构造函数可以简化

  Player(String name, int color) {
    this._color = color;
    this._name = name;
  }

  Player(this._name, this._color);

命名构造函数也可以通过以 _

Named constructors can also be private by starting the name with _

class Player {
  Player._(this._name, this._color);

  Player._foo();
}

具有 final 的构造函数字段初始化程序列表是必需的:

Constructors with final fields initializer list are necessary:

class Player {
  final String name;
  final String color;

  Player(this.name, this.color);

  Player.fromPlayer(Player another) :
    color = another.color,
    name = another.name;
}

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

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