任何人都可以告诉我如何在ActionScript3.0中创建一个如下所示的函数吗?如何在ActionScript 3中创建一个接受多个参数类型的函数?
function test(one:int){ trace(one);}
function test(many:Vector<int>){
for each(var one:int in many){ test(one); }
}
任何人都可以告诉我如何在ActionScript3.0中创建一个如下所示的函数吗?如何在ActionScript 3中创建一个接受多个参数类型的函数?
function test(one:int){ trace(one);}
function test(many:Vector<int>){
for each(var one:int in many){ test(one); }
}
您可以使用星号和is
关键字:
function test(param:*):void
{
if(param is int)
{
// Do stuff with single int.
trace(param);
}
else if(param is Vector.<int>)
{
// Vector iteration stuff.
for each(var i:int in param)
{
test(i);
}
}
else
{
// May want to notify developers if they use the wrong types.
throw new ArgumentError("test() only accepts types int or Vector.<int>.");
}
}
这是很少的好有两个分离的,明确标记的方法,因为它很难说出什么方法的意图没有特定的类型要求。
我建议一组更清晰的方法,例如适当地命名。
function testOne(param:int):void
function testMany(param:Vector.<int>):void
在这种特殊情况下可能有用的东西是...rest
参数。这样,您可以允许一个或多个整数,并为其他人(以及后来自己)提供更多的可读性,以了解该方法的用途。
Thanks。想要让我的FlashDevelop解析参数类型(如果可以的话),但是我要为它创建2个函数。 – Elonoa 2013-02-27 02:20:42
@Elonoa现实的你应该为你做任何事情。如果你正在自己的工作,并且你有信心,你可以回想起你的功能在赛道上的作用,那么这很好。如果你在许多大型项目上工作,并且经常让其他人像我一样进行更新,那么清晰度就非常重要,你应该可以使用分离的方法。 – Marty 2013-02-27 02:45:37
另外,如果您使用的是FlashDevelop,这里是使用您自己的评论来使用代码提示的好地方。 – Marty 2013-02-27 02:54:19
function test(many:*):void {
//now many can be any type.
}
在使用Vector
的情况下,这也应该工作:
function test(many:Vector.<*>):void {
//now many can be Vector with any type.
}
构造函数重载在AS3中不受支持,但是您可以使用泛型类型参数function test(foo:*):void { – 2013-02-26 21:39:38