你能在 classes 中创建辅助函数而不实例化那个 class 的对象吗?

Can you make helper functions in classes without instantiating an object of that class?

我有一个 class,它具有用于实例化对象的功能,但我知道其他语言将在 class 中具有辅助函数,这些 public 没有定义一个明确的对象。

DART 语言网站似乎并没有真正解决这个问题。在一个简单的情况下,它可能类似于拥有一个 Point class,然后在其中拥有一个 jsondecoder,这可能有一些用处,而不是需要包含其他库。

class Point {
  int x, y;
  Point(this.x, this.y);

  Point fromMap(HashMap<String, int> pt){
    return new Point(pt["x"]||null, pt["y"]||null);
  }
}

这样当我需要使用点 class 时,我可以说:

Point pt = Point.fromMap({});

当我翻阅 classes 以正确制作这些内容时,我并没有真正看到任何示例 public。

查找静态修饰符:static Point fromMap(...) 如果 Dart 有这样的功能。

Dart 允许在 class 上定义静态成员。你的情况:

class Point {
  int x, y;
  Point(this.x, this.y);

  static Point fromMap(Map<String, int> pt) {
    return new Point(pt["x"], pt["y"]);
  }
}

值得注意的是,您还可以使用命名构造函数 and/or 工厂构造函数 :

class Point {
  int x, y;
  Point(this.x, this.y);

  // use it with new Point.fromMap(pt)
  Point.fromMap(Map<String, int> pt) : this(pt["x"], pt["y"]);

  // use it with new Point.fromMap2(pt)
  factory Point.fromMap2(Map<String, int> pt) => new Point(pt["x"], pt["y"]);
}

给定的示例可能不是最好的,因为所需的结果是新的 Point。命名构造函数 - 正如 Alexandre 在他的回答中所说 - 是这种情况下的首选解决方案。

也许更好的例子(但仍然有点人为)是:

library Points;

class Point {

  ...

  /// Return true if data in pt is valid [Point] data, false otherwise. 
  bool isValidData(HashMap<String, int> pt) { ... }
}

在没有 first-class 函数的语言中(例如 Java),静态方法是合适的。 Dart 也支持这个。

class Point {

  ...

  /// Return true if data in pt is valid [Point] data, false otherwise. 
  static bool isValidData(HashMap<String, int> pt) { ... }
}

由于 Dart 有第一个 class 个函数,在库中定义的函数可能是更好的选择。

library Points;

bool isValidPointData(HashMap<String, int> pt) { ... }

class Point {
  ...
}