我的自定义Class事件不起作用。 这是我的代码:
public delegate void ChangedEventHandler(object sender, EventArgs e, int p);
当我不使用delegate { }
时,我收到错误:
对象引用未设置为Object的实例。
public event EventHandler DownloadCompleted = delegate { };
public event ChangedEventHandler DownloadProgressChanged = delegate { };
public void DownloadFile(String url, String localFilename)
{
try
{
Application.DoEvents();
WebRequest req = WebRequest.Create(url);
WebResponse response = req.GetResponse();
Stream stream = response.GetResponseStream();
byte[] downloadedData = new byte[0];
int downloaded = 0;
byte[] buffer = new byte[1024];
int totalData = (int)response.ContentLength;
int a = 0;
FileStream file = File.Create(localFilename);
while (true)
{
if (paused == false)
{
Application.DoEvents();
int bytesRead = stream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
file.Flush();
file.Close();
DownloadCompleted(this, new EventArgs());
break;
}
file.Write(buffer, 0, bytesRead);
downloaded += bytesRead;
DownloadProgressChanged(this, EventArgs.Empty, downloaded);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
在其他类中使用:
Downloader dw = new Downloader();
dw.DownloadFile(txt_url.Text, txt_path.Text);
dw.DownloadCompleted += dw_DownloadCompleted;
dw.Changed +=dw_Changed;
void wb_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Completed!");
}
void wb_DownloadProgressChanged(object sender,DownloadProgressChangedEventArgs e)
{
//Setting ProgressBar Value
progressBar1.Maximum = 100;
progressBar1.Value = e.ProgressPercentage;
}
但ProgressBar无效。
我的代码出了什么问题?
答案 0 :(得分:3)
您必须在"其他"中分配事件处理程序。在调用前强
DownloadFile
:
Downloader dw = new Downloader();
dw.DownloadCompleted += dw_DownloadCompleted;
dw.Changed +=dw_Changed;
dw.DownloadFile(txt_url.Text, txt_path.Text);
您也不需要分配= delegate { }
等空事件处理程序。
否则在DownloadFile
尝试呼叫DownloadCompleted
和Changed
事件处理程序时 - 它们是空引用,这就是您收到该错误的原因。分配空事件处理程序会阻止NullReferenceException
,但由于您要为事件分配空事件处理程序 - 它们显然什么都不做。