您想拥有多个构造函数的情况如何?例如,您希望使用2个构造函数:
Customer(String name, int age, String location) {
this.name = name;
this.age = age;
this.location = location;
}
Customer(this.name, this.age) {
this.name = name;
this.age = age;
}
但是,如果您同时在一个类中定义它们,则将出现编译器错误。
Dart提供了Named构造函数,可帮助您更清晰地实现多个构造函数:
class Customer {
Customer(String name, int age, String location) {
this.name = name;
this.age = age;
this.location = location;
}
Customer.withoutLocation(this.name, this.age) {
this.name = name;
this.age = age;
}
Customer.empty() {
name = "";
age = 0;
location = "";
}
@override
String toString() {
return "Customer [name=${this.name},age=${this.age},location=${this.location}]";
}
}
您可以使用语法糖更简单地编写它:
Customer(this.name, this.age, this.location);
Customer.withoutLocation(this.name, this.age);
Customer.empty() {
name = "";
age = 0;
location = "";
}
现在我们可以Customer
通过这些方法创建新对象。
var customer = Customer("bezkoder", 26, "US");
print(customer);
var customer1 = Customer.withoutLocation("zkoder", 26);
print(customer1);
var customer2 = Customer.empty();
print(customer2);
那么,有什么方法可以使Customer.empty()
整洁?而且打电话时如何初始化位置字段为空值Customer.withoutLocation()
,而不是null
?
来自:多个构造函数
color
和而name
不是getColor()
和getName()
方法使用getter 。如果值永远不变,则可以使用单个公共字段,例如class Player { final String name; final int color; Player(this.name, this.color); }
。