如何在 Dart 中创建私有变量? [英] How to create private variables in Dart?
问题描述
我想创建一个私有变量,但我不能.
这是我的代码:
void main() {var b = new B();b.testB();}A类{int_private = 0;测试A(){print('int 值:$_private');_私人 = 5;}}B 类扩展 A {字符串_私有;测试B(){_private = '你好';print('字符串值:$_private');测试A();print('字符串值:$_private');}}
当我运行这段代码时,我得到以下结果:
字符串值:你好整数值:你好打破异常:int"类型不是value"的String"类型的子类型.
我在编辑此源代码时也没有收到任何错误或警告.
如何在 Dart 中创建私有变量?
来自 Dart 文档:
<块引用>与 Java 不同,Dart 没有关键字 public、protected 和 private.如果标识符以下划线 _
开头,则它对其库是私有的.
库不仅提供 API,而且是一个隐私单元:以下划线开头的标识符 _
仅在库内部可见.
关于图书馆的几句话:
<块引用><块引用>每个 Dart 应用程序都是一个库,即使它不使用库指令.import 和 library 指令可以帮助您创建模块化和可共享的代码库.
您可能听说过 part
指令,它允许您将一个库拆分为多个 Dart 文件.
I want to create a private variable but I cannot.
Here is my code:
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.
How can I create a private variable in Dart?
From Dart documentation:
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.
Libraries not only provide APIs, but are a unit of privacy: identifiers that start with an underscore _
are visible only inside the library.
A few words about libraries:
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.
You may have heard of the part
directive, which allows you to split a library into multiple Dart files.
这篇关于如何在 Dart 中创建私有变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!