例如,打击将输出Instance of 'Point'。是否可以将其重新格式化为某种形式Point(x: 0, y: 0)?
class Point {
final int x;
final int y;
Point(this.x, this.y);
}
void main() {
final zero = Point(0, 0);
print(zero); // Instance of 'Point'
}
Run Code Online (Sandbox Code Playgroud)
在Python中,有__repr__和__str__ 。在Java中,有toString. 在 Swift/ObjC 中,有description. 飞镖中相当于什么?
您可以覆盖toString方法:
class Point {
final int x;
final int y;
Point(this.x, this.y);
@override
String toString(){
return "Point(x: $x, y: $y)";
}
}
void main() {
final zero = Point(0, 0);
print(zero); // Point(x: 0, y: 0)
}
Run Code Online (Sandbox Code Playgroud)
它打印你想要的字符串。
| 归档时间: |
|
| 查看次数: |
1001 次 |
| 最近记录: |