【问题标题】:Why are my getters not called when I'm trying to access a field from outside the class?当我尝试从课堂外访问字段时,为什么不调用我的吸气剂?
【发布时间】:2019-03-28 15:29:33
【问题描述】:

我开始了解 Haxe,我主要使用它来生成 Python 代码和 C# DLL。

但是我多次遇到相同的问题:每当我尝试编写 getter 时,当我从方法内部访问相关属性时它们工作正常,但是当我尝试从类外部访问它们时它们是甚至没有打电话。我开始怀疑我错过了一些基本的东西。

例如,如果我编写以下类:

@:expose
@:keep
class TestClass
{
    public var testField(get, null):String;

    private function get_testField():String
    {
        trace("executing getter");
        return "testString";
    }

    public function new() {}

    public function testMethod()
    {
        trace(testField);
    }
}

然后在 Python 中:

testInstance = MyModule.TestClass();
testInstance.testMethod();

...按预期输出:

executing getter
testString

但是

print(testInstance.testField)

...输出None

我期待testInstance.testField 在所有情况下都返回"testString",我做错了什么?这也发生在 C# 中。

【问题讨论】:

    标签: properties haxe


    【解决方案1】:

    这是因为properties in Haxe are a compile-time feature 并不会生成原生属性。并非所有目标都具有属性,而且那些确实可能不会 100% 匹配 Haxe 的语义。

    相反,在编译时调用访问器方法(get_field()set_field())代替了属性访问。因此,

    trace(testField);
    

    编译成Python后变成如下:

    print(str(self.get_testField()))
    

    因此,为了获得一致的结果,您还必须在 Python 端调用 get_testField()

    对于 C# 和 Flash 目标,有生成原生属性的元数据(请参阅haxe --help-metas):

    @:property - 将要编译的属性字段标记为本机 C# 属性(仅限 cs)

    @:getter -(类字段名称)在给定字段上生成本机 getter 函数(仅限 Flash)

    @:setter -(类字段名称)在给定字段上生成本机 setter 函数(仅限 Flash)

    请注意,C# 目标的 @:property 仅适用于没有 physical field 的属性。在您的示例中,(get, null) 必须替换为 (get, never) 才能正常工作。

    目前还有一个open feature request 用于通过@:property 支持JS 目标上的本机属性。考虑到 Python 也具有原生属性,这对 Python 也可能有意义。也许考虑打开一个问题。 :)

    【讨论】:

    • 非常感谢,这很有道理!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    相关资源
    最近更新 更多