我不明白为什么这不起作用:
try
{
//Give Message of Command
NewMessageEventArgs e = new NewMessageEventArgs("COMMAND", "Download File", "RETR");
OnNewMessageReceived(this, e);
byte[] buffer = new byte[2048];
int read = 0;
Int64 TotalBytesRead = 0;
Int64 FileSize = this.GetFileSize(sourceFilename);
DownloadCanceled = false;
do
{
if (DownloadCanceled)
{
NewMessageEventArgs CancelMessage = new NewMessageEventArgs("RESPONSE", "Download Canceled.", "CANCEL");
DownloadCanceled = false;
OnNewMessageReceived(this, CancelMessage);
return false;
}
read = DownloadResponseStream.Read(buffer, 0, buffer.Length);
DownloadFileStream.Write(buffer, 0, read);
TotalBytesRead += read;
//Declare Event
DownloadProgressChangedArgs DownloadProgress = new DownloadProgressChangedArgs(TotalBytesRead, FileSize);
//Progress changed, Raise the event.
OnDownloadProgressChanged(this, DownloadProgress);
System.Windows.Forms.Application.DoEvents();
} while (!(read == 0));
//Get Message and Raise Event
NewMessageEventArgs NewMessageArgs = new NewMessageEventArgs("RESPONSE", DownloadResponse.StatusDescription, DownloadResponse.StatusCode.ToString());
OnNewMessageReceived(this, NewMessageArgs);
//Declare Event
DownloadCompletedArgs Args = new DownloadCompletedArgs("Successful", true);
//Raise Event
OnDownloadCompleted(this, Args);
DownloadResponseStream.Close();
DownloadFileStream.Flush();
DownloadFileStream.Close();
DownloadFileStream = null;
DownloadResponseStream = null;
}
catch (Exception ex)
{
//catch error and delete file only partially downloaded
DownloadFileStream.Close();
//delete target file as it's incomplete
targetFI.Delete();
//Decalre Event for Error
DownloadCompletedArgs DownloadCompleted = new DownloadCompletedArgs("Error: " + ex.Message, false);
//Raise Event
OnDownloadCompleted(this, DownloadCompleted);
}
}
结果我得到了不确定的结果。
我一直在鼓励自己: JavaScript closure inside loops – simple practical example
我知道这是一个范围问题,所以我正在尝试创建一个闭包,我不能在这里找到什么?
提前致谢!
答案 0 :(得分:3)
你要返回的最后一个函数是你正在调用的最后一个函数,并且它只用()
调用,这意味着没有参数,但是你已经在内部函数中指定了一个参数,并且它是{{ 1}}。
undefined
只是不要在内部函数中指定一个参数,而外部函数的参数将在范围内,并且是封闭的(闭包)
function returnVerse(x){
// ^ outer argument
return function(x) {
// ^ inner argument overwrites outer argument
console.log(x); // undefined
};
}
for(var x = 9; x>=0; x--){
return returnVerse(x)();
// ↑ ^ innner argument not passed, "undefined"
outer argument
}
此外,从function returnVerse(x){
return function() {console.log(x);};
}
for(var x=9; x>=0; x--){
returnVerse(x)();
}
循环返回毫无意义,并且意味着它只运行一次