我习惯于使用委托事件处理程序进行事件回调,但现在我尝试使用事件操作来调用事件。我找不到太多关于如何在任何地方正确使用它的信息,所以我希望有人能指出我正确的方向。
我有一个处理字符串对象的 Action 事件处理程序。在我的订阅者类中,我有public event Action<string> UploadProgress;
.事件处理程序的调用方式如下:
UploadProgress.Invoke(string.Format("sending file data {0:0.000}%", (bytesSoFar * 100.0f) / totalToUpload));
侦听器类订阅此事件,如下所示:
uploadFile.UploadProgress += uploadFile_UploadProgress;
void uploadFile_UploadProgress(string obj)
{
var prog = obj;
}
调用事件时,我得到System.NullReferenceException: Object reference not set to an instance of an object
.我不确定我需要在订阅者类中更改什么以避免此错误。有人可以告诉我使用事件操作的正确方法或为我提供链接,我可以在哪里阅读它吗?我知道如何使用正常的操作,但对将其声明为事件感到困惑。任何帮助,不胜感激。
这种方式要好得多,通过事件发送bytesToUpload和totalToUpload,而不是整个Action(右示例):
internal class Program
{
private static void Main(string[] args)
{
SomeClass someClass = new SomeClass();
someClass.UploadProgress += SomeClass_UploadProgress;
someClass.DoSomeUpload();
}
private static void SomeClass_UploadProgress(object sender, UploadEventArgs e)
{
string s = string.Format("sending file data {0:0.000}%", (e.BytesSoFar * 100.0f) / e.TotalToUpload);
Console.WriteLine(s);
}
}
public class UploadEventArgs : EventArgs
{
public float BytesSoFar { get; set; }
public float TotalToUpload { get; set; }
}
public class SomeClass
{
public event EventHandler<UploadEventArgs> UploadProgress;
public void DoSomeUpload()
{
if (UploadProgress != null)
{
UploadEventArgs e = new UploadEventArgs();
e.BytesSoFar = 123f;
e.TotalToUpload = 100000f;
UploadProgress.Invoke(this, e);
}
}
}