飞镖多个构造函数
发布时间:2020-12-14 14:55:15 所属栏目:百科 来源:网络整理
导读:是否真的不可能为dart中的类创建多个构造函数? 在我的Player类中,如果我有这个构造函数 Player(String name,int color) { this._color = color; this._name = name;} 然后我尝试添加这个构造函数: Player(Player another) { this._color = another.getColo
是否真的不可能为dart中的类创建多个构造函数?
在我的Player类中,如果我有这个构造函数 Player(String name,int color) { this._color = color; this._name = name; } 然后我尝试添加这个构造函数: Player(Player another) { this._color = another.getColor(); this._name = another.getName(); } 我收到以下错误:
我不是通过创建一个带有一堆非必需参数的构造函数来寻找解决方法. 有没有一个很好的方法来解决这个问题? 解决方法
您只能拥有一个未命名的构造函数,但是您可以拥有任意数量的其他命名构造函数
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); 命名构造函数也可以是私有的,用_开头的名字 class Player { Player._(this._name,this._color); Player._foo(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |