如何将匿名函数直接注入枚举



对于Dart 2.17,可以像使用类一样在enum中使用构造函数。

我试图在枚举中直接插入一个匿名函数。

这里的代码工作,但不完全是我想要的。

int _add(int a, int b) => a + b;
int _sub(int a, int b) => a - b;
int _mul(int a, int b) => a * b;
double _div(int a, int b) => a / b;
enum MyEnum {
addition(_add),
subtract(_sub),
multiplication(_mul),
division(_div);
final Function fx;
const MyEnum(this.fx);
}
void main() {
var fun = MyEnum.addition;
print(fun.fx(1, 2));
fun = MyEnum.subtract;
print(fun.fx(1, 2));
fun = MyEnum.multiplication;
print(fun.fx(1, 2));
fun = MyEnum.division;
print(fun.fx(1, 2));
}

不是在代码的其他地方创建一个函数,如_add, _sub, _mul, _div,我想直接将一个匿名函数插入到enum中,就像下面的代码一样(请注意下面的代码不起作用)。

我想做什么

enum MyEnum {
// I'd like to insert an anonymous function instead.
addition((int a, int b) => _add(a, b)), 
subtract((int a, int b) => a - b),
multiplication(int a, int b) => a * b),
division((int a, int b) => a / b;);
final Function fx;
const MyEnum(this.fx);
}

有可能吗?有人能告诉我怎么做吗?我不知道我做错了什么。

Dart 2.17的一个特点是您不再需要使用扩展。下面的代码包含了Dart 2.17的特性,这是我解决这个问题的方法。虽然这肯定不像我在原帖中所希望的那样优雅和令人满意。

enum MyEnum {
addition(),
subtract(),
multiplication(),
division();
Function fx() {
switch (this) {
case addition:
return (int a, int b) => a + b;
case subtract:
return (int a, int b) => a - b;
case multiplication:
return (int a, int b) => a * b;
case division:
return (int a, int b) => a / b;
default:
throw Exception('Unknown operation');
}
}
const MyEnum();
}
void main() {
var fun = MyEnum.addition;
print(fun.fx()(1, 2));
fun = MyEnum.subtract;
print(fun.fx()(1, 2));
fun = MyEnum.multiplication;
print(fun.fx()(1, 2));
fun = MyEnum.division;
print(fun.fx()(1, 2));
}

您尝试过扩展吗?我不确定你是否能做到你想做的一切(就像发生在我身上的那样),但他们几乎完成了任务。有时我只需要调用扩展而不是枚举,可能是当我在扩展上放置一些静态方法时(比如调用SexExt.staticMethod()而不是Sex.staticMethod),但我发现它们非常有用。

enum Sex { MALE, FEMALE }
extension SexExt on Sex {
String getText() {
switch (this) {
case Sex.MALE:
return "Maschio";
case Sex.FEMALE:
return "Femmina";
}
}
String getShortText() {
switch (this) {
case Sex.MALE:
return "M";
case Sex.FEMALE:
return "F";
}
}
}

最新更新