Actionscript 3.0 交换
是否可以在 ActionScript 3.0 中实现类似于 C++ std::swap 的交换例程? 我的意思是
public static function Swap(var a, var b):void
{
var c = a;
a = b;
b = c;
}
,然后
var a:int = 3;
var b:int = 5;
Swap(a,b);
trace(a, " ", b); // there must be 5 3
对于整数来说,它不能“按原样”工作,因为它们是按值传递的,而不是引用到交换例程中的。
Is it possible to implement swapping routine in ActionScript 3.0 similar to C++ std::swap?
I mean something like
public static function Swap(var a, var b):void
{
var c = a;
a = b;
b = c;
}
and then
var a:int = 3;
var b:int = 5;
Swap(a,b);
trace(a, " ", b); // there must be 5 3
It doesn't work "as is" for integers because they're passed by value, not ref into the Swap routine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不幸的是,您无法以这种方式实现交换,因为 ActionScript 3、Java 和许多其他语言 按值传递基元和对象引用。该链接将为您提供详细信息,但基本上这意味着函数内部的引用与函数外部的引用不同(即使它们确实引用相同的对象)。因此,摆弄函数中的参数引用对函数外没有任何影响。您被迫进行内联交换。
如果您确实需要在函数中进行一些交换行为,则必须将参数包装在另一个对象中,然后您可以更改内部引用:
Unfortunately you can't implement a swap in this way, because ActionScript 3, Java, and many other languages pass primitives and object references by value. That link will give you the details, but basically this means that the references inside the function aren't the same as the references outside the function (even though they indeed refer to the same object). Therefore, fiddling with the parameter references in the function has no effect outside the function. You're forced to do the swap inline.
If you really needed some swap behavior in a function, you'd have to wrap the parameters in another object, and then you can change the inner reference:
遗憾的是,Actionscript 总是按值传递基元,并且总是按引用传递对象(如果我错了,请有人纠正我)。
你能做的就是将你的原语包装成一个对象。
我知道...这很丑陋,并且不适合大多数情况...
¹ 事实上,这不是真的,因为引用不同,但指向同一个对象,与基元相反,引用指向不同的原始值。
Sadly, Actionscript always pass primitives by value, and always pass objects by reference¹ (someone correct me if I'm wrong).
What you can do is wrap your primitive into a object.
I know... This is ugly and won't fit in most of the cases...
¹ In fact, it isn't true, as the references are different but points to the same object, contrary to primitives, that the references points to different primitive values.
如果您可以对 SWF 进行后处理,则可以使用
Apparat 工具
创建宏
:http:// code.google.com/p/apparat/wiki/MacroExpansion它甚至已经存在一个到
BitMacro
的交换方法:http://www.google.com/codesearch/p?hl=en#3GyOvBpuCbk/apparat-ersatz/src/main/as3/apparat/math/ BitMacro.as&q=swap%20package:http://apparat%5C.googlecode%5C.com&sa=N&cd=3&ct=rc
If you can postprocess your SWF you can use
Apparat tools
to create aMacro
: http://code.google.com/p/apparat/wiki/MacroExpansionit even already exists a swap method into the
BitMacro
:http://www.google.com/codesearch/p?hl=en#3GyOvBpuCbk/apparat-ersatz/src/main/as3/apparat/math/BitMacro.as&q=swap%20package:http://apparat%5C.googlecode%5C.com&sa=N&cd=3&ct=rc