如何通过它的uid获取对象?

时间:2011-11-19 23:43:48

标签: actionscript-3 flex reflection

有没有办法通过它的UID获取对象,以便以下代码可以工作?

当函数完成时,property" xxx"应该是"字符串二"不是"字符串一"。

// Test class
public function test():void {
    this.xxx = "string one";
    foo.bar(this.xxx);
    trace(this.xxx); // Prints: string two
}

// Foo class
public function bar(value:*):void {
    // ... What would I have to do here to get the property, not its value?
    value = "string two";
}

4 个答案:

答案 0 :(得分:0)

无法更改函数的参数(对变量的引用)。它不是指针。您可以为其分配其他变量,但不会更改传递给该函数的参数。但是你可以改变参数的属性:

class Test {
    public var xxx:String;

    public function test():void {
        this.xxx = "string one";
        foo.bar(this);
        trace(this.xxx); // Prints: string two
    }
}


class Foo {
    public function bar(test:Test):void {
        test.xxx = "string two";
    }
}

当然,为了实现这一目标,班级Foo必须知道Test以及要更改的属性。这使得一切都不那么动态,也许不是你想要的。这是一个你可以使用Interface的情况。或者您可能希望坚持使用常见模式,例如使用getter并将值分配给适当的属性:

class Test {
    public var xxx:String;

    public function test():void {
        this.xxx = "string one";
        this.xxx = foo.getValue();
        trace(this.xxx); // Prints: string two
    }
}


class Foo {
    public function getValue():String{
        return "string two";
    }
}

答案 1 :(得分:0)

使用Box括号怎么样?我知道这不是OO做事的方式,但Action脚本支持它,它看起来像是一个很好的选择。

class Test {
public var xxx:String;

public function test():void {
    this.xxx = "string one";
    foo.bar(this,"xxx"); // actual name of property as string ;litral
    trace(this.xxx); // Prints: string two
  }
}

class Foo {
public function bar(test:*,prop:String):void {
    //test could be from any class . 
    test[prop] = "string two";
  }
}

这应该可以解决问题。但是你需要确保调用“bar”方法的代码传递一个有效的对象,该对象具有定义的“xxx”属性,因为此代码不再是类型安全的。

答案 2 :(得分:0)

要获取属性,最简单的方法是将属性封装到对象中,将其传递给函数,然后检索它:

// Test class
public function test():void {
    var obj: Object = new Object();
    obj.variable = "string one";
    foo.bar(obj);
    trace(obj.variable); // Prints: string two
}

// Foo class
public function bar(value:Object):void {
    value.variable = "string two";
}

但你为什么要这样做呢?只需做xxx = foo.bar();

就可以在各方面做得更好

答案 3 :(得分:0)

传递由值

将变量传递给函数时,会复制变量。退出后,您对变量所做的任何更改都不会反映出来。

传递通过引用

将变量传递给函数时,会传递变量的“指针”。您对变量所做的任何更改都将被复制。

在AS3中,所有内容都是按引用传递,除了基元(Boolean,String,int,uint等),它们在幕后具有特殊操作符,使它们像传递一样-值。由于xxx是一个字符串,这就是正在发生的事情。 (另外,字符串是不可变的;你实际上不能改变它们的值。)

如何修复它(正如其他人所说):

  • Test对象本身传递给bar()函数:bar( this );
  • xxx参数封装在自己的对象中并传递:bar( {prop:this.xxx} );
  • bar()返回值并设置它:this.xxx = bar();
相关问题