ActionScript 运算符为

发布于 2024-10-18 09:11:08 字数 716 浏览 5 评论 0原文

有人对 as 运算符有很好的解释吗?

一方面,在我看来,使用 as 通常比实例化一个新对象更好。

但有些情况下,这个操作员会让我失望。例如,通过 URLLoader:

private function completeHandler(event:Event):void {
    var loader:URLLoader = URLLoader(event.target);
    trace("completeHandler: " + loader.data);

    var x:XML = new XML(loader.data);
    trace("x=" + x);
}

为什么我必须在这里使用构造函数?为什么我不能说 var x:XML = loader.data as XML; 并节省一些内存?

感谢您的任何见解! 亚历克斯

does anybody have a good explanation of the as operator?

On one hand it seems to me, that it is often better to use as instead of instantiating a new object.

But then there are situations, when this operator let's me down. For example when loading a text file in XML format through an URLLoader:

private function completeHandler(event:Event):void {
    var loader:URLLoader = URLLoader(event.target);
    trace("completeHandler: " + loader.data);

    var x:XML = new XML(loader.data);
    trace("x=" + x);
}

Why do I have to use a constructor here? Why can't I say var x:XML = loader.data as XML; and save some memory?

Thank you for any insights!
Alex

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

累赘 2024-10-25 09:11:08

as 评估变量的类型是另一个类的超类还是子类。它不会创建新对象。与 is 的区别在于,is 返回布尔值,而 as 返回所需类型的对象,或者 null< /代码>。它用于类型转换。

请参阅 ActionScript 文档

一个典型的用例是在舞台上使用 MovieClip,它通过实例名称检索:

// This will not compile:
var d:DisplayObject = stage.getChildByName ("instance1"); 
d.gotoAndPlay (2);

// This will play the MovieClip from frame 2
var m : MovieClip = stage.getChildByName ("instance1") as MovieClip;
m.gotoAndPlay (2); 

stage.getChildByName() 始终返回一个 DisplayObject,无论它是否确实是一个 MovieClip、Sprite、Button 等。因此,如果您想使用MovieClip类的任何方法,您需要首先输入cast to MovieClip。但是,这不会创建新的 MovieClip,而只是确保您使用正确的类型。

as evaluates whether a variable's type is a super class or subclass of another class. It does not create a new object. The difference to is being that while is returns a Boolean value, as returns either an object of the desired type, or null. It is used for type casts.

See the ActionScript documentation.

A typical use case would be using a MovieClip on the stage, which is retrieved by instance name:

// This will not compile:
var d:DisplayObject = stage.getChildByName ("instance1"); 
d.gotoAndPlay (2);

// This will play the MovieClip from frame 2
var m : MovieClip = stage.getChildByName ("instance1") as MovieClip;
m.gotoAndPlay (2); 

stage.getChildByName() always returns a DisplayObject, regardless if it's really a MovieClip, Sprite, Button, etc. So if you want to use any of class MovieClip's methods, you need to type cast to MovieClip first. This does not, however, create a new MovieClip but simply ensures that you are using the correct type.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文