如何在 dart 中重载 String 上的 + 运算符?

How can I overload the + operator on String in dart?

我试图在 String class 上重载 + 运算符,以便能够将 int 添加到 String。 'A'+1 应该产生 'B'。但它在飞镖上不起作用。我怎样才能让它发挥作用?

extension StringExt on String {
  String operator +(int i) {
    return String.fromCharCode(this.codeUnitAt(0) + i);
  }
}

void main() {
  String s = 'A';
  print('A' + 1);
}

您不能在 String 上添加名为 + 的扩展方法,因为 String 已经有一个名为 + 的运算符。

Dart 在每个 class 上只能有一个成员(没有成员 重载 ),并且扩展成员的优先级低于现有实例成员。

您实际上可以调用扩展 +,但您需要显式调用扩展以避免 String.operator+ 优先:

 print(StringExt('A') + 1);

这消除了短运算符的大部分优势。

如上所述,您可以使用不同的名称:

extension CharCodeInc on String {
  String operator /(int i) => String.fromCharCode(codeUnitAt(0) + i);
}
...
  print("A"/2); // prints "C"

可惜所有好名字都被占用了(字符串上至少 +*)。