在 Actionscript 3 (Flex) 中扩展数组
我正在尝试对 Array 进行变体以达到非常特定的目的。当我有以下问题时:
public class TileArray extends Array {
// Intentionally empty - I get the error regardless
}
为什么我不能这样做?
var tl:TileArray = [1,2,3];
尽管我可以做到这一点,但
var ar:Array = [1,2,3];
我收到的错误是这样的:
将静态类型数组的值隐式强制为可能不相关的类型
I'm trying to make a variation on Array for a very specific purpose. When I have the following:
public class TileArray extends Array {
// Intentionally empty - I get the error regardless
}
Why can't I do this?
var tl:TileArray = [1,2,3];
despite the fact that I can do this
var ar:Array = [1,2,3];
The error I receive is this:
Implicit coercion of a value with static type Array to a possibly unrelated type
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以编写自己的类来公开 Array 的所有方法,而不是扩展 Array。通过使用 Proxy 类,您可以将所有默认数组方法重定向到内部数组,但仍然可以灵活地添加您自己的方法:
例如:
Instead of extending Array you could write your own class that exposes all the methods of Array. By employing the Proxy class you can redirect all default Array methods to an internal array but still have the flexibility to add your own methods:
example:
[] 只创建一个数组。它不能用于创建 Array 的子类。
使用新功能“扩展”数组的好方法是编写操作常规数组的独立实用程序函数。最重要的是,这将允许您对任何数组执行任何操作,而不仅限于使用您的子类创建的数组。
下面是一个包含数组实用函数的类的简单示例:
用法:
[] only creates an Array. It cannot be used to create a subclass of Array.
The good way to "extend" Array with new functionality is to write standalone utility functions that manipulate regular Arrays. Best of all, this will allow you to do anything to any Array and not be limited only to Arrays created using your subclass.
Here's a simple example of a class that contains utility functions for Arrays:
Usage:
[1,2,3]
是new Array(1,2,3)
的简写(或语法糖)。考虑到这一点,代码失败的原因似乎就更明显了。每个
TileArray
都是一个Array
,因为TileArray
扩展了Array
,但反之则不然:不是每个>Array
是一个TileArray
。因此,您不能在需要TileArray
的地方传递Array
。这就是您收到编译器错误的原因。转换只会将错误从编译时推迟到运行时,因为对象的实际类型是 Array,这确实与 TileArray 无关。
如果您想扩展 Array 功能(并且还能够添加一些语法糖),您可能需要考虑扩展 Proxy,正如已经建议的那样。请记住,它的性能较差,因此如果您打算大量使用此类,这可能不是最好的主意。
[1,2,3]
is shorthand (or syntactic sugar) fornew Array(1,2,3)
. With that in mind, it seems more apparent why your code fails.Every
TileArray
is anArray
, sinceTileArray
extendsArray
, but the inverse is not true: not everyArray
is aTileArray
. So, you can't pass anArray
where aTileArray
is expected. That's why you get the compiler error.Casting will only defer the error from compile-time to run-time, since the actual type of your object is
Array
, which is indeed unrelated toTileArray
.If you want to extend
Array
functionality (and also be able to add some syntactic sugar), you might want to look into extendingProxy
, as it was already suggested. Keep in mind it's less performant, so if you plan to use this class heavily, this might not be the best idea.