誰かがActionScript3.0で以下のように機能する関数を作成する方法を教えてもらえますか?
function test(one:int){ trace(one);}
function test(many:Vector<int>){
for each(var one:int in many){ test(one); }
}
誰かがActionScript3.0で以下のように機能する関数を作成する方法を教えてもらえますか?
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>.");
}
}
特定のタイプ要件がないと、そのメソッドの意図が何であるかを判断するのが難しい場合があるため、これは、2つの別個の明確にラベル付けされたメソッドを持つよりも良いアプローチになることはめったにありません。
適切な名前が付けられた、より明確なメソッドのセットを提案します。
function testOne(param:int):void
function testMany(param:Vector.<int>):void
この特定の状況で役立つ可能性のあるものは、...rest
議論です。このようにして、1つ以上のintを許可し、他の人(および後で自分自身)がメソッドの機能を理解できるように、もう少し読みやすくすることができます。
function test(many:*):void {
//now many can be any type.
}
を使用する場合Vector
、これも機能するはずです。
function test(many:Vector.<*>):void {
//now many can be Vector with any type.
}