代码之家  ›  专栏  ›  技术社区  ›  Fallenreaper

您可以在类中创建助手函数而不实例化该类的对象吗?

  •  5
  • Fallenreaper  · 技术社区  · 10 年前

    我有一个类,它有实例化对象的函数,但我知道其他语言在类中有助手函数,这些函数是公共的,没有显式定义对象。

    DART语言网站似乎并没有真正解决这个问题。在一个简单的例子中,它可以是一个Point类,然后在里面有一个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);
      }
    }
    

    这样,当我需要使用Point类时,我可以说:

    Point pt = Point.fromMap({});
    

    我真的没有看到任何例子,说明我什么时候在课堂上翻来翻去,把这些内容适当地公开。

    3 回复  |  直到 10 年前
        1
  •  10
  •   Alexandre Ardhuin    10 年前

    Dart允许在类上定义静态成员。在您的情况下:

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

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

    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"]);
    }
    
        2
  •  2
  •   Argenti Apparatus    10 年前

    给定的示例可能不是最好的,因为期望的结果是一个新的 Point 。正如亚历山大在回答中所说,命名构造函数是本例中的首选解决方案。

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

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

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

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

    由于Dart具有一流的函数,所以在库中定义的函数可能是更好的选择。

    library Points;
    
    bool isValidPointData(HashMap<String, int> pt) { ... }
    
    class Point {
      ...
    }
    
        3
  •  1
  •   dKen baraa yusri    5 年前

    查找静态修改器: static Point fromMap(...) 如果Dart有这样的设施。