通过字符串Haxe参考对象 [英] Haxe Reference Object via String
问题描述
在Haxe中,我试图通过变量访问对象的值.在JavaScript中,您可以使用 []
对其进行访问,但是在Haxe中,此方法将不起作用,并返回错误:
In Haxe, I am trying to access an object's value via a variable. In JavaScript you use [ ]
to access it, but in Haxe this doesn't work and comes back with an error:
字符串应为Int
String should be Int
在{x:Int,name:String}上不允许数组访问
Array access is not allowed on { x : Int, name : String }
我需要最后一行代码的帮助:
I need help with the last line of code:
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
推荐答案
您要尝试执行的操作称为 反映
API:
What you're trying to do is called Reflection, and the way to do that in Haxe is via the Reflect
API:
var results = Reflect.field(room, "name");
如果您想访问 static
字段,则将 Class< T>
作为第一个参数而不是实例:
If you want to access a static
field instead, pass the Class<T>
as the first argument instead of an instance:
class Foo {
public static var bar = 0;
}
var bar = Reflect.field(Foo, "bar");
对于具有吸气剂的属性,您需要使用<改为使用href ="https://api.haxe.org/Reflect.html#getProperty" rel ="nofollow noreferrer"> getProperty()
.
For properties with a getter, you'll want to use getProperty()
instead.
注意:反射通常被认为是不好的做法,因为它会将错误从编译转移到运行时,并且本质上是类型不安全的.通常,有更好的方法来解决问题,但是在没有更多上下文的情况下,很难在这里推荐具体的解决方案.
Note: Reflection is generally considered bad practice as it moves errors from compile- to runtime and is inherently type-unsafe. There are usually better ways to solve a problem, but it's hard to recommend a concrete solution here without more context.
这篇关于通过字符串Haxe参考对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!