gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:40:33 27 4
gpt4 key购买 nike

我有一个类,它具有用于实例化对象的函数,但我知道其他语言将在类内部具有辅助函数,这些函数是公共(public)的,无需明确定义对象。

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({});

我真的没有看到任何关于我什么时候翻阅类(class)以使这些正确公开的例子。

最佳答案

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"]);
}

关于dart - 您可以在类中创建辅助函数而不实例化该类的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34882028/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com