ActionScript:是否有充分的理由使用“as"转换? [英] ActionScript: Is there ever a good reason to use 'as' casting?

查看:25
本文介绍了ActionScript:是否有充分的理由使用“as"转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我对 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)

另外,如果我在这里错了,请纠正我,as 转换将返回类的实例或 null,而类名"转换将返回要么返回类的实例,要么在无法进行强制转换时引发异常——除此之外,它们是相同的.

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.

考虑到这一点,as 强制转换似乎严重违反了快速失败的原则......而且我很难想象这种情况会更可取使用 as 类型转换而不是类名类型转换(可能还包含一个 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).

所以,我的问题是:在什么情况下最好使用 as 转换?

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

推荐答案

在两种情况下需要使用 as 进行转换:转换为 Date 和转换为一个 Array.

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

对于日期,调用 Date(xxx) 的行为与 new Date().toString() 相同.

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

对于数组,调用 Array(xxx) 将创建一个 Array,其中包含一个元素:xxx.

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

Class() 转换方法已被​​证明比 as 转换更快,因此当效率很重要时它可能比 as 更可取(以及不使用日期和数组时).

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).

`

这篇关于ActionScript:是否有充分的理由使用“as"转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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