如何在Dart创建私有变量? [英] How in Dart create private variable?

查看:305
本文介绍了如何在Dart创建私有变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建私有变量,但我不能。

I want create 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('Srting value: $_private');
    testA();
    print('Srting value: $_private');
  }
}



当我运行此代码时,得到以下结果:

When I run this code, I get the following result:

Srting 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 I can create private variable in Dart?

推荐答案



From Dart documentation:


与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创建私有变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆