gpt4 book ai didi

dart - Dart 有类变量的概念吗?

转载 作者:行者123 更新时间:2023-12-03 02:46:14 25 4
gpt4 key购买 nike

在遍历 A Tour of the Dart Language 时我在 Constructors 中看到这个例子部分:

class Point {
num x, y;

Point(num x, num y) {
// There's a better way to do this, stay tuned.
this.x = x;
this.y = y;
}
}

谈论实例变量。来自 Python,这最初让我有点困惑,因为我认为 num x, y; 是一种类变量。

Dart有类变量的概念吗?

最佳答案

不确定“类变量”是什么意思。
我假设您指的是静态变量。

静态变量在每个类中存在一次,而实例变量在每个实例中存在一次。

class Point {
static num x, y;

fooMethod() {
print('$x, $y');
}
}

在声明它们的类中,无需前缀即可访问它们。从其他任何地方都可以使用姓氏作为声明它们的前缀来访问它们。

void main() {
print(Point.x);
}

对于子类,声明字段的类前缀也是必需的,因为它们不是继承的。

class CustomPoint extends Point {

barMethod() {
print('${Point.x}, ${Point.y}');
}
}

关于dart - Dart 有类变量的概念吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50966609/

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