企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
存取器方法的可见性不会影响属性的可得到与否。也就是说,如果一个属性是 public 的而且定义为有一个 getter ,不管如何 那个getter 会自我定义为private。 > Visibility of accessor methods has no effect on the accessibility of its property. That is, if a property is public and defined to have a getter, that getter may me defined as private regardless. getter 和setter 可以访问它们的数据存储的物理字段。编译器确保这类的字段访问,如果从存取器方法本身做出,不会通过存取器方法,从而避免无限递归: > Both getter and setter may access their physical field for data storage. The compiler ensures that this kind of field access does not go through the accessor method if made from within the accessor method itself, thus avoiding infinite recursion: ~~~ class Main { public var x(default, set):Int; function set_x(newX) { return x = newX; } static public function main() {} } ~~~ 然而,编译器只有如果至少一个访问标识符是default或者null的时候假设一个物理字段存在。 > However, the compiler assumes that a physical field exists only if at least one of the access identifiers is default or null. **物理字段** >[warning] 定义:物理字段 > 一个字段在如下任何一个情况被认为是物理的: > 一个变量(第4.1节) > 一个属性(第4.2节)带有 读取访问或者写入访问标识符为default或者null > 一个属性带有 :isVar 元数据(第6.9节) >[warning] Definition: Physical field A field is considered to be physical if it is either >[warning] * a variable (4.1) >[warning] * a property (4.2) with the read-access or write-access identifier being default or null >[warning] * a property (4.2) with :isVar metadata (6.9) 如果不是这种情况,从一个存取器内部访问字段导致一个编译错误: > If this is not the case,access to the field from within an accessor method causes a compilation error: ~~~ class Main { // This field cannot be accessed because it is not a real variable public var x(get, set):Int; function get_x() { return x; } function set_x(x) { return this.x = x; } static public function main() {} } ~~~ 如果一个物理字段是真实准备的,它可以通过归于讨论的字段被强制与 :isVar 元数据。 > If a physical field is indeed intended,it can be forced by attributing the field in question with the :isVar metadata (6.9): ~~~ class Main { // @isVar forces the field to be physical allowing the program to compile. @:isVar public var x(get, set):Int; function get_x() { return x; } function set_x(x) { return this.x = x; } static public function main() {} } ~~~ >[warning] **花絮**:属性的 setter 类型 并不少见新的Haxe用户被setter的类型需要是T->T而不是看起来更自然的T->Void类型惊讶到。毕竟,为什么一个setter需要返回些什么呢?基本原理是,我们仍然想要可以是i用字段分配使用setter为右手表达式。给定一个链如 x=y=1 ,执行为 x=(y=1) 。为了赋值y=1的结果到x,形式必须有一个值。如果 y 有一个setter 返回Void,这是不可能的。 >[warning] Trivia: Property setter type It is not uncommon for new Haxe users to be surprised by the type of a setter being required to be T->T instead of the seemingly more natural T->Void. After all, why would a setter have to return something? The rationale is that we still want to be able to use field assignments using setters as rightside expressions. Given a chain like x = y = 1, it is evaluated as x = (y = 1). In order to assign the result of y = 1 to x, the former must have a value. If y had a setter returning Void, this would not be possible.