Dart:实例变量是私有类还是私有类中的公共变量? [英] Dart: should the instance variables be private or public in a private class?

查看:336
本文介绍了Dart:实例变量是私有类还是私有类中的公共变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

class _Foo {
    String _var1;
    String var2;
}

我总是使用公共变量 var2 ,因为我认为在类已经是私有的时候就没有必要创建私有变量,因为无论如何您都无法访问私有类。

I always use public variable var2 because I think it's no point to make private variables when the class is already private, because you can not access private class anyway.

但是我发现很多人使用私有变量 _var1 。这只是个人喜好吗?当类是私有的时,私有实例变量的意义何在?如果您不能访问私有类,则无论它们是否是私有的,您都无法访问其所有实例变量。如果可以在同一lib中访问私有类,则可以访问其所有实例变量,无论它们是否是私有的。

But I found many people use private variable _var1. Is this just a personal preference? When the class is private, what is the point of private instance variable? If you can not access the private class, you can not access all of its instance variables regardless whether they are private or not. If you can access the private class in the same lib, then you can access its all instance variables regardless whether they are private or not.

推荐答案

将类设为私有不会使其成员变为私有,也不会使该类的实例不可访问。

Making the class private doesn't make its members private and it doesn't make instances of that class inaccessible.

假设

lib / private_class.dart

class Foo {
  final _PrivateClass privateClass = _PrivateClass();
}

class _PrivateClass {
  String publicFoo = 'foo';
  String _privateBar = 'bar';
}

bin / main.dart

import 'package:so_53495089_private_field_in_private_class/private_class.dart';

main(List<String> arguments) {
  final foo = Foo();
  print(foo.privateClass.publicFoo);
//  print(foo.privateClass._privateBar); // invalid because of ._privateBar
}

而无效私有类的类型,或在另一个库中扩展或实现该类,或创建该类的实例
,但除此之外没有太大区别。

You can't declare variables or parameters of the type of a private class or extend or implement the class in another library or create an instance of that class, but otherwise there is not much difference.

因此,如果应该向API用户隐藏该字段(内部状态),则将该字段设为私有。

So if the field is supposed to be hidden (internal state) to users of the API, then make the field private.

这篇关于Dart:实例变量是私有类还是私有类中的公共变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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