我有一个类,它具有实例化对象的功能,但我知道其他语言将在类中具有公共的辅助函数,而不显式定义对象.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
当我需要使用Point类时,我可以这样说:
Point pt = Point.fromMap({});
Run Code Online (Sandbox Code Playgroud)
我没有真正看到任何关于我何时翻阅课程以使这些正确公开的例子.
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"]);
}
}
Run Code Online (Sandbox Code Playgroud)
值得注意的是,您还可以使用命名构造函数和/或工厂构造函数:
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"]);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
361 次 |
| 最近记录: |