我以为我在 AS3 中找到了引用资料,但以下行为让我感到困惑:
// declarations for named individual reference later on
var myAmbientSound:Sound;
var myAmbientSoundLocation:String = "http://ambient_sound_location";
var myPeriodicSound:Sound;
var myPeriodicSoundLocation:String = "http://periodic_sound_location";
var myOccasionalSound:Sound;
var myOccasionalSoundLocation:String = "http://occasional_sound_location";
// for iterating through initialization routines
var mySoundArray:Array = [myAmbientSound, myPeriodicSound, myOccasionalSound];
var mySoundLocation:Array = [myAmbientSoundLocation, myPeriodicSoundLocation, myOccasionalSoundLocation];
// iterate through the array and initialize
for(var i:int = 0; i < mySoundArray.length; i++) {
mySoundArray[i] = new Sound();
mySoundArray[i].load(new URLRequest(mySoundLocation[i]));
}
在这一点上,我认为
mySoundArray[0]
会引用与 myAmbientSound
相同的对象;但是,访问 myAmbientSound
会引发空指针异常,而 mySoundArray[0]
会按预期工作并引用 Sound
对象。我在这里误解了什么?
最佳答案
它更像是 java 引用变量而不是 C 指针。
var myAmbientSound:Sound;
var myPeriodicSound:Sound;
var myOccasionalSound:Sound;
//these variables are not initialized and hence contain null values
现在您创建一个包含这些变量的当前值(空)的数组
var mySoundArray:Array = [myAmbientSound, myPeriodicSound, myOccasionalSound];
该数组现在包含三个空值
[null, null, null]
,而不是您期望它包含的三个指向 Sound
对象的指针。现在,当您调用
mySoundArray[0] = new Sound();
时,会创建一个新的 Sound
对象,并将其地址分配给数组的第一个位置 - 它不会修改 myAmbientSound
变量。
关于flash - Actionscript 3 - 引用与值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2281320/