Try*_*ard 5 constructor named-constructor dart flutter
我想知道是否可以检查我使用哪个构造函数在 dart 的 if 语句中创建创建的元素。
我想做的一个简单的例子:
class Employee {
int id;
String name;
String title;
Employee.id(this.id);
Employee.name(this.name);
Employee.title(this.title);
}
Run Code Online (Sandbox Code Playgroud)
现在我的代码中有一个 if 语句,想要检查我是否使用了构造函数 Employee.id。在这种情况下,我会做一些事情,就像这样:
Employee e = new Employee.id(1)
//check if e was created with Employee.id constructur
if (e == Emploee.id) {
print(e.id)
} else {
print("no id")
}
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?谢谢您的回答。
您可以定义私有枚举属性来设置这样的私有信息,并稍后使用函数打印它。另外不要忘记用 来标记你的构造函数factory。
enum _ConstructorType {
Identifier,
Name,
Title,
}
class Employee {
int id;
String name;
String title;
_ConstructorType _constructorType;
factory Employee.id(id) {
return Employee._privateConstructor(_ConstructorType.Identifier, id: id);
}
factory Employee.name(name) {
return Employee._privateConstructor(_ConstructorType.Name, name: name);
}
factory Employee.title(title) {
return Employee._privateConstructor(_ConstructorType.Title, title: title);
}
Employee._privateConstructor(this._constructorType,
{this.id, this.name, this.title});
String constructorDescription() {
return this._constructorType.toString();
}
}
Run Code Online (Sandbox Code Playgroud)
如果您不需要此信息作为字符串,而是作为枚举,您可以随时删除其上的下划线,并将此信息公开以供您在课堂外使用。
| 归档时间: |
|
| 查看次数: |
1013 次 |
| 最近记录: |