通过字符串的 Haxe 引用对象

标签 haxe

在 Haxe 中,我试图通过变量访问对象的值。在 JavaScript 中,您使用 [ ] 来访问它,但在 Haxe 中,这不起作用并返回错误:

String should be Int

Array access is not allowed on { x : Int, name : String }

我需要最后一行代码的帮助:

var room = { x: 10, name: 'test' };

trace(room.name);   // this works returns 'test' 

// how do I reference foo to return 'test' as the above result.
var foo = "name";
var results = room[foo];   // need fixing

最佳答案

您要执行的操作名为 Reflection ,而在 Haxe 中执行此操作的方法是通过 Reflect 应用程序接口(interface):

var results = Reflect.field(room, "name");

如果你想访问一个static字段,传递 Class<T>作为第一个参数而不是实例:

class Foo {
    public static var bar = 0;
}

var bar = Reflect.field(Foo, "bar");

对于 properties有了 setter/getter ,你会想要使用 getProperty() 相反。


注意:反射通常被认为是不好的做法,因为它将错误从编译转移到运行时,并且本质上是类型不安全的。 通常有更好的方法来解决问题,但如果没有更多上下文,很难在这里推荐具体的解决方案。

关于通过字符串的 Haxe 引用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37225974/

相关文章:

haxe - 在Haxe中执行外部程序中的URL/路径

haxe - 如何强制 Haxe 编译所有源类?

ios - 是否可以在 ios 和 android 中使用 haxe nme 构建 opengl 游戏?

haxe - Haxe 中有某种退出语句吗?

haxe - Haxe 可以用于创建库吗?

迭代器(不是迭代器)上的 Lambda 迭代

python - 为了使用编译后的 Haxe 对象,我的 Python 程序应该包含什么?

php - haxe (php) https 调用 : stream_socket_client() Peer certificate CN did not match expected CN

android - HaxeFlixel - Hello World with android 不会启动/关闭

networking - Haxe+实时网络