gpt4 book ai didi

dart - 覆盖 Dart 中的 getter 功能?

转载 作者:行者123 更新时间:2023-12-03 02:50:05 24 4
gpt4 key购买 nike

我想在 dart 中声明一个字段,并且只覆盖 getter 的功能,但我不确定如何/如果可能的话。

class Pony {
String ponyGreeting;
String ponyName;
Pony(this.ponyGreeting, this.ponyName);

String get ponyGreeting => "$ponyGreeting I'm $ponyName!";
}

但这会导致错误,因为我已经定义了“ponyGreeting”。我不能只删除字段 ponyGreeting,因为我想使用构造函数设置它,如果我创建了一个 setter ,我将不得不在某处设置该值,而且我真的不想要一个多余的属性。

最佳答案

您可以在 getter 旁边使用私有(private)变量:

class Pony {
String _ponyGreeting;
String ponyName;
Pony(this._ponyGreeting, this.ponyName);

String get ponyGreeting => "$_ponyGreeting I'm $ponyName!";
}

关于dart - 覆盖 Dart 中的 getter 功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21544468/

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