使用事件提升事件<t>

时间:2016-07-09 02:34:13

标签: c# event-handling action

我曾经使用委托EventHandler进行事件回调,但现在我试图使用事件Action来调用事件。我无法找到关于如何在任何地方正确使用它的信息,所以我希望有人能指出我正确的方向。

我有一个处理字符串对象的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。我不确定在订阅者类中需要更改什么以避免此错误。有人可以告诉我使用事件动作的正确方法,或者提供我可以阅读的链接吗?我知道如何使用正常的Action,但对将其声明为事件感到困惑。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

这种方式要好得多,通过事件发送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);
      }
    }
  }