dart - 我可以在 Dart 中的任何类上使用扩展方法吗?

标签 dart extension-methods

我正在尝试为 Decimal 类编写扩展方法:

void parse() {
  Decimal two = Decimal.two;
}

extension on Decimal {
  static Decimal get two => Decimal.fromInt(2);
}

然而,Dart 说“没有为类 Decimal 定义 getter 'two'。”扩展方法是否仅适用于 Dart 原生类?

谢谢!

最佳答案

在您的导入中使用以下代码行:

import 'YourFileName.dart' show ExtensionName;

在你的“YourFileName.dart”中应该是这样的:
extension  ExtensionName on Decimal {
  static Decimal get two => Decimal.fromInt(2);
}

然后根据您的要求使用它。

让我知道您是否仍然使用 卡在任何地方扩展 Dart .

关于dart - 我可以在 Dart 中的任何类上使用扩展方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59433532/

相关文章:

通用数组的 C# 扩展方法

ios - 扩展程序-错误(Swift3)

android - 如何将 flutter 的日期选择器值添加到文本字段?

angularjs - ng-repeat 仅适用于迭代 List 而不是 Iterable 或 Set

dart - 为什么 flutter 中的 open_file 无法打开我的应用程序中的任何文件?

flutter - 即使在 Dart 中有下划线,如何制作公共(public)属性(property)?

c# - 为什么 IEnumerable 上没有 ForEach 扩展方法?

c# - lambda 表达式中的变量如何赋值

c# - 为什么要在 Method<type>() 中指定 <type> ?以及如何使用它?

flutter - 与Javascript Math.sign等效但与Dart等效