[英]How do I check if an element was created with a named constructor in dart?
我想知道是否可以在 dart 的 if 语句中检查我使用哪个构造函数来创建创建的元素。
我想做的一个简单的例子:
class Employee {
int id;
String name;
String title;
Employee.id(this.id);
Employee.name(this.name);
Employee.title(this.title);
}
现在我的代码中有一个 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")
}
有没有办法做到这一点? 谢谢您的回答。
您可以为您定义私有枚举属性来设置这样的私有信息,并稍后使用 function 打印它。 也不要忘记用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();
}
}
如果您需要此信息不是作为字符串,而是作为枚举,您始终可以删除其上的下划线,并将此信息公开以供您在 class 之外使用。
您可以使用冻结的 package 使您的 class 成为Union type
,并使用如下所示的折叠方法来查看使用了什么构造函数:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'tst.freezed.dart';
@freezed
abstract class Employee with _$Employee {
const factory Employee.id(int id) = IdEmployee;
const factory Employee.name(String name) = NameEmployee;
const factory Employee.title(String title) = TitleEmployee;
}
void main() {
Employee employee1 = Employee.id(0);
Employee employee2 = Employee.name('some name');
Employee employee3 = Employee.title('some title');
employee1.when(
id: (int id) => print('created using id contsrutor and id= $id'),
name: (String name) => print('created using name const and name = $name'),
title: (String title)=>print('created using title const and title = $title'),
);//prints the first statement
employee2.when(
id: (int id) => print('created using id contsrutor and id= $id'),
name: (String name) => print('created using name const and name = $name'),
title: (String title)=>print('created using title const and title = $title'),
);//prints the second statement
employee3.when(
id: (int id) => print('created using id contsrutor and id= $id'),
name: (String name) => print('created using name const and name = $name'),
title: (String title)=>print('created using title const and title = $title'),
);//prints the third statement
print(employee1 is IdEmployee);
print(employee1 is NameEmployee);
}
output 将是:
created using id contsrutor and id= 0
created using name const and name = some name
created using title const and title = some title
true
false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.