如何在Dart中创建私有变量? [英] How to create private variables in Dart?
问题描述
我想创建一个私有变量,但我不能。
I want to create a private variable but I cannot.
这是我的代码:
void main() {
var b = new B();
b.testB();
}
class A {
int _private = 0;
testA() {
print('int value: $_private');
_private = 5;
}
}
class B extends A {
String _private;
testB() {
_private = 'Hello';
print('String value: $_private');
testA();
print('String value: $_private');
}
}
运行此代码时,得到以下结果:
When I run this code, I get the following result:
String value: Hello
int value: Hello
Breaking on exception: type 'int' is not a subtype of type 'String' of 'value'.
在编辑此源代码时,我也没有收到任何错误或警告。
Also I not get any error or warnings when editing this source code.
如何在Dart中创建私有变量?
How can I create a private variable in Dart?
推荐答案
来自Dart文档:
与Java不同,Dart没有关键字public,protected和private。如果标识符以下划线
_
开头,则该标识符是其库专用的。
Unlike Java, Dart doesn’t have the keywords public, protected, and private. If an identifier starts with an underscore
_
, it’s private to its library.
库不仅提供API,而且是隐私的单位:以下划线 _
开头的标识符仅在库内部可见。
Libraries not only provide APIs, but are a unit of privacy: identifiers that start with an underscore _
are visible only inside the library.
关于库的几句话:
每个Dart应用程序都是一个库,即使它不使用库指令。导入和库指令可以帮助您创建模块化且可共享的代码库。
Every Dart app is a library, even if it doesn’t use a library directive. The import and library directives can help you create a modular and shareable code base.
听说过 part
指令,它使您可以将库拆分为多个Dart文件。
You may have heard of the part
directive, which allows you to split a library into multiple Dart files.
这篇关于如何在Dart中创建私有变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!