是否有办法通过某些“宏功能调用”将null
设置为调用实例?
像这样:
class A {
// ...
macro function DestroyItself() {
// ...
}
}
var a:A = new A();
// ...
a.DestroyItself();
trace(a); // "null"
答案 0 :(得分:4)
是的:
macro public function destroy(self:Expr) {
return macro $self = null;
}
// ...
a.destroy();
在非静态宏函数中,第一个Expr
参数是对调用者实例的引用。
答案 1 :(得分:3)
一旦方法是为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();
})();