【问题标题】:Haxe macro to set null to calling instance?Haxe 宏将 null 设置为调用实例?
【发布时间】:2017-06-28 07:45:19
【问题描述】:

由于某些“宏函数调用”,有没有办法将null 设置为调用实例?

像这样:

class A {
    // ...
    macro function DestroyItself() {
        // ...
    }
}

var a:A = new A();
// ...
a.DestroyItself();
trace(a); // "null"

【问题讨论】:

    标签: macros haxe


    【解决方案1】:

    是的:

    macro public function destroy(self:Expr) {
        return macro $self = null;
    }
    // ...
    a.destroy();
    

    在非静态宏函数中,第一个 Expr 参数是调用者实例的引用。

    【讨论】:

    • macro public function destroy(self:haxe.macro.Expr) {... import haxe.macro.Expr;
    【解决方案2】:

    曾经的方法是为null 任何实例创建通用工具。

    package ;
    
    class Tools
    {
        /**
         *  Simply assigns null to the instance
         *  See more at: http://code.haxe.org/category/macros/generating-code-in-a-macro.html
         *  
         *  @param instance - Any
         *  @return haxe.macro.Expr
         */
        public static macro function nullMe(instance : haxe.macro.Expr.ExprOf<Dynamic>) : haxe.macro.Expr
        {
            return macro {
                ${instance} = null;
            };
        }
    }
    

    这使用using Tools; 来一般null 任何实例,但我会推荐这个。我会使用每类方法。

    Main.hx

    package ;
    
    class Main {
    
        static function main() {
            // Construct
            var instance = new SomeClass();
    
            // Destroy
            instance.destroy();
    
            // Trace null
            trace(instance);
        }
    }
    

    SomeClass.hx

    package ;
    
    class SomeClass
    {
        public function new()
        {
            trace("Hello from SomeClass!");
        }
    
        private function preDestroy()
        {
            trace("The end is nigh!");
        }
    
        public macro function destroy(self : haxe.macro.Expr) : haxe.macro.Expr
        {
            return macro {
                @:privateAccess ${self}.preDestroy();
                ${self} = null;
            };
        }
    }
    

    编译好的 JS

    // Generated by Haxe 3.4.2
    (function () { "use strict";
    var Main = function() { };
    Main.main = function() {
        var instance = new SomeClass();
        instance.preDestroy();
        instance = null;
        console.log(instance);
    };
    var SomeClass = function() {
        console.log("Hello from SomeClass!");
    };
    SomeClass.prototype = {
        preDestroy: function() {
            console.log("The end is nigh!");
        }
    };
    Main.main();
    })();
    

    【讨论】:

    • @:privateAccess ${self}.preDestroy(); 是否可以检查该类是否具有preDestroy 功能?
    • 它应该足够直截了当,但我认为你不需要它,因为在类上实现了 destroy 宏。所以可以肯定地假设它会在那里。
    • 我在使用这种解决方案时会小心。它可能会导致“难以阅读”的代码。销毁事物时,将引用归零是最后一步。还有一个事实是,将局部变量归零是没有用的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 2016-12-25
    相关资源
    最近更新 更多