1 code-reuse enums implements dart
我想创建 2 个具有相同字段的枚举(甚至更多),以及与之相关的相同方法,例如:
enum Enum1 {
A1('A1', 1),
B1('B1', 2);
String name;
int x1;
Enum1(this.name, this.x1);
String concat(String s) {
return name + s;
}
}
enum Enum2 {
A2('A2', 3),
B2('B2', 4);
String name;
int x2;
Enum2(this.name, this.x2);
String concat(String s) {
return name + s;
}
}
Run Code Online (Sandbox Code Playgroud)
我应该怎么做才能在不同的枚举中重用相同方法的代码?
name即,如何重用与concat上一个示例相关的代码?
我尝试使用一个类来实现两个枚举,但它不断提示我必须在每个枚举中分别重新实现方法concat和 getter name。
我失败的尝试是这样的:
class Reuse {
String name;
String concat(String s) {
return name + s;
}
}
enum Enum1 implements Reuse {
A1('A1',1), B1('B1',2);
int x1;
String name;
Enum1(this.name, this.x1);
String concat(String s);
}
enum Enum2 implements Reuse {
A2('A2',3), B2('B2',4);
int x2;
String name;
Enum2(this.name, this.x2);
String concat(String s);
}
Run Code Online (Sandbox Code Playgroud)
这可以通过声明Reuse为mixin并将枚举声明为而with Reuse不是 来实现implements Reuse。
关键字implements不会继承方法的实现,而extendsdowith会为您提供方法的实现。由于 dart 中的枚举被限制使用extends,因此这with成为唯一的选择,并且您只能with与 mixin 一起使用。
mixin Reuse {
String get name;
String concat(String s) {
return name + s;
}
}
enum Enum1 with Reuse {
A1('A1', 1),
B1('B1', 2);
final int x1;
final String name;
const Enum1(this.name, this.x1);
}
enum Enum2 with Reuse {
A2('A2', 3),
B2('B2', 4);
final int x2;
final String name;
const Enum2(this.name, this.x2);
}
void main() {
print(Enum1.A1.concat('example'));
print(Enum2.A2.concat('example'));
}
Run Code Online (Sandbox Code Playgroud)