Flex/Actionscript:动态访问静态变量 [英] Flex/Actionscript: Dynamically accessing static var
问题描述
假设我有一个 Foo 类:
Let's say that I have a class Foo:
public class Foo
{
public static var bar:String = "test";
}
如何在运行时使用字符串Foo"或/和 Foo 的实例和字符串bar"来引用 bar?
How can I reference bar at runtime using the string "Foo" or/and and instance of Foo and the string "bar"?
即
var x:Object = new Foo();
...
x["bar"]
...不起作用,IntelliJ 中的调试模式让我充满希望,因为 bar 被列为属性.
...doesn't work, debug mode in IntelliJ got my hopesup as bar gets listed as a property.
更新:
请注意,在行动点",我在编译时对 foo 一无所知.我需要通过字符串Foo"和bar"来解析 Foo.bar.
Note that at the "point of action" I don't know anything about foo in compile time. I need to resolve Foo.bar through the strings "Foo" and "bar".
换言之,因为 flex 没有 eval 我怎样才能完成与 eval("Foo.bar") 相同的功能?
Of put differently, as flex don't have eval how can I accomplishe the same as eval("Foo.bar")?
推荐答案
它是一个静态变量,因此您将无法使用 foo 的实例来访问它;它是静态访问的,使用 ClassName.variableName 表示法,如下所示:
It's a static variable, so you won't be able to access it using an instance of foo; it's accessed statically, using ClassName.variableName notation, like so:
trace(Foo.bar);
trace(Foo.bar);
//产生:测试"
同样,因为您已将 Foo 和 bar 都声明为 public,所以您应该能够从应用程序的任何位置以这种方式访问 Foo.bar.
As well, because you've declared both Foo and bar public, you should be able to access Foo.bar that way from anywhere in your application.
更新:啊,我明白你在问什么.您可以使用 flash.utils.Summary.getDefinitionByName():
Update: Ah, I see what you're asking. You can use flash.utils.Summary.getDefinitionByName():
// Either this way
trace(getDefinitionByName("Foo").bar);
// Or this
trace(getDefinitionByName("Foo")["bar"]);
...后者感谢 Jeremy 的回答,这对我来说是新的.:)
... the latter thanks to Jeremy's answer, which was new to me. :)
这篇关于Flex/Actionscript:动态访问静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!