gpt4 book ai didi

Dart 私有(private)属性(property)

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

有人说私有(private)属性可用于更改类定义,而无需根据之前的类更改现有代码。

例如;

main() {
var p1 = new Project();
p1.name = 'Breeding';
p1.description = 'Managing the breeding of animals';
print('$p1');
// prints: Project name: Breeding - Managing the breeding of animals
}

class Project {
String name, description;

toString() => 'Project name: $name - $description';
}

现在,使用私有(private)变量将类 Project 更改如下。

main() {
var p1 = new Project();
p1.name = 'Breeding';
p1.description = 'Managing the breeding of animals';
print('$p1');
// prints: Project name: BREEDING - Managing the breeding of animals
var p2 = new Project();
p2.name = 'Project Breeding of all kinds of animals';
print("We don't get here anymore because of the exception!");
}

class Project {
String _name; // private variable
String description;

String get name => _name == null ? "" : _name.toUpperCase();
set name(String prName) {
if (prName.length > 20)
throw 'Only 20 characters or less in project name';
_name = prName;
}

toString() => 'Project name: $name - $description';
}

这是什么意思;

(due to the private properties introduced) The code that already existed in main (or in general, the client code that uses this property) does not need to change



上述代码(Learning Dart)的作者说,由于新插入的私有(private)属性(_name),现有的'main()'等代码不受Project类中属性变化的影响。

这是我无法理解的。现有类中新插入的私有(private)属性如何成为根据这些类保持其他代码不受影响或安全的一种方式?

最佳答案

我仍然不知道你的实际问题是什么。

您可以使用私有(private)字段、类和函数/方法来重新组织(重构)您的代码和
只要公共(public) API 不受影响并且库的用户不依赖于类的内部行为,用户就不应该识别更改。
隐私主要是一种通信媒介,表明某些成员(公共(public))旨在由 API 用户访问,而私有(private)成员是 API 用户不应该关心的实现细节。
不要将隐私与安全混为一谈。反射通常允许访问私有(private)成员。

如果这不是您要寻找的答案,请添加评论或改进您的问题。

关于 Dart 私有(private)属性(property),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25635454/

31 4 0