动作:是否有过使用“为”铸造一个很好的理由? [英] ActionScript: Is there ever a good reason to use 'as' casting?

查看:94
本文介绍了动作:是否有过使用“为”铸造一个很好的理由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解的ActionScript中,有两种类型转换的:

From what I understand of ActionScript, there are two kinds of casts:

var bar0:Bar = someObj as Bar;  // "as" casting
var bar1:Bar = Bar(someObj); // "class name" casting (for want of a better name)

此外,并请纠正我,如果我错了这里,铸造要么返回类的实例或,而类名铸要么返回类的实例或抛出一个异常,如果转换是不可能的 - 除了这一点,它们是相同的。

Also, and please correct me if I'm wrong here, as casting will either return an instance of the class or null, while "class name" casting will either return an instance of the class or raise an exception if the cast is impossible – other than this, they are identical.

鉴于这一点,虽然,铸造似乎是大规模侵犯的快速失败 - 失败 - 早期的原则......而我无法想象一个情况下这将是preferable使用投,而不是一个类名铸(有可能的话,一个的instanceof 扔在那里)。

Given this, though, as casting seems to be a massive violation of the fail-fast-fail-early principle... And I'm having trouble imagining a situation where it would be preferable to use an as cast rather than a class name cast (with, possibly, an instanceof thrown in there).

所以,我的问题是:在什么情况下会是preferable使用铸造

So, my question is: under what circumstances would it be preferable to use as casting?

推荐答案

您需要使用来投在两种情况下:强制转换为日期,并转换成一阵列

You need to use as to cast in two scenarios: casting to a Date, and casting to an Array.

有关日期,调用日期(XXX)的行为一样新的日期()的toString()

For dates, a call to Date(xxx) behaves the same as new Date().toString().

对于数组,调用阵列(XXX)将创建一个阵列有一个元素:XXX

For arrays, a call to Array(xxx) will create an Array with one element: xxx.

类()铸造方法已被证明是比得更快铸造,因此它可能是preferable到时的效率问题(当不工作的日期和阵列)。

The Class() casting method has been shown to be faster than as casting, so it may be preferable to as when efficiency matters (and when not working with Dates and Arrays).

import flash.utils.*;

var d = Date( 1 );

trace( "'" + d, "'is type of: ",getQualifiedClassName( d ) );

var a:Array = Array( d );

trace( "'" + a, "' is type of: ", getQualifiedClassName( a ) );

    //OUTPUT
        //'Mon Jun 15 12:12:14 GMT-0400 2009 'is type of:  String
        //'Mon Jun 15 12:12:14 GMT-0400 2009 ' is type of:  Array

    //COMPILER ERRORS/WARNINGS:
        //Warning: 3575: Date(x) behaves the same as new Date().toString(). 
        //To cast a value to type Date use "x as Date" instead of Date(x).
        //Warning: 1112: Array(x) behaves the same as new Array(x).
        //To cast a value to type Array use the expression x as Array instead of Array(x).

`

这篇关于动作:是否有过使用“为”铸造一个很好的理由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆