是否真的不可能为dart中的类创建多个构造函数?
在我的播放器类中,如果我有这个构造函数
Player(String name, int color) {
this._color = color;
this._name = name;
}
Run Code Online (Sandbox Code Playgroud)
然后我尝试添加这个构造函数:
Player(Player another) {
this._color = another.getColor();
this._name = another.getName();
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
已定义默认构造函数.
我不是通过创建一个带有一堆非必需参数的构造函数来寻找解决方法.
有没有一个很好的方法来解决这个问题?
Gün*_*uer 71
您只能拥有一个未命名的 构造函数,但是您可以拥有任意数量的其他命名构造函数
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);
Run Code Online (Sandbox Code Playgroud)
这个构造函数可以简化
Player(String name, int color) {
this._color = color;
this._name = name;
}
Run Code Online (Sandbox Code Playgroud)
至
Player(this._name, this._color);
Run Code Online (Sandbox Code Playgroud)
命名构造函数也可以是私有的,可以使用 _
class Player {
Player._(this._name, this._color);
Player._foo();
}
Run Code Online (Sandbox Code Playgroud)
如果您已经在项目中使用了带参数的构造函数,现在您发现需要一些无参数的默认构造函数,您可以添加一个空构造函数。
class User{
String name;
User({this.name}); //This you already had before
User.empty(); //Add this later
}
Run Code Online (Sandbox Code Playgroud)
如果您的班级使用最终参数,则接受的答案将不起作用。这样做:
class Player {
final String name;
final String color;
Player(this.name, this.color);
Player.fromPlayer(Player another) :
color = another.color,
name = another.name;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16164 次 |
| 最近记录: |