【问题标题】:Dart Encapsulation - private dataDart封装——私有数据
【发布时间】:2023-02-06 22:04:42
【问题描述】:

我知道我可以通过在其名称前加上下划线 (_) 来创建私有属性。

但是如果我把类和主函数放在同一个文件中我可以访问私人财产

class User {
  late String email;
  late String _password;

  User({required String email, required String password})
      : email = email,
        _password = password;
}

void main() {
  User u = User(email: 'myemail@gmail.com', password: 'mypassword');
  print(u._password); // I can access to this private property
}

如果我将 User 类移动到一个单独的文件中,一切都会像预期的那样工作,并且我无法访问私有属性

import 'user.dart';
void main() {
  User u = User(email: 'myemail@gmail.com', password: 'mypassword');
  print(u._password); // I can't access to this private property
}

我不明白原因。

【问题讨论】:

    标签: dart


    【解决方案1】:

    如果你想从一个类中访问一个变量,使用这个

    class User {
      late String email;
      late String _password;
    
      User({required String email, required String password})
          : email = email,
            _password = password;
    
      //this is called a get function, which you can call from class instance.
      String get getUserPassword => _password;
    }
    
    import 'user.dart';
    void main() {
      User u = User(email: 'myemail@gmail.com', password: 'mypassword');
      print(u.getUserPassword); // changes here
    }
    

    编码快乐!!

    【讨论】:

      猜你喜欢
      • 2021-11-17
      • 2020-11-09
      • 2020-03-07
      • 1970-01-01
      • 2018-07-25
      • 2014-06-18
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多