簡體   English   中英

引發自定義事件時出錯

[英]Error when raising custom event

我有一個會寫日志的類。 班級需要引發一個事件(在特定情況下(以下未指出)),班級將對此事件做出反應。 我有下面的代碼,但是一旦嘗試引發該事件,就會在指示的行上收到錯誤消息,

你調用的對象是空的

知道我缺少什么嗎?

//1. Class where event is registered
    public class LogEvent
    {
        public delegate void WriteLogEventHandler(object Sender, WriteLogEventArgs e);
        public event WriteLogEventHandler WriteLog;

        public class WriteLogEventArgs : EventArgs
        {
            public string Message { get; set; }

            public WriteLogEventArgs(string message) : base()
            {
                Message = message;
            }
        }

        //Raise the event.
        internal void OnWriteLog(WriteLogEventArgs e)
        {
             WriteLog(this, e);    //Error here.  Seems like WriteLog is null
        }

//2. Class where event is raised.
public class Logs
{
    public static void WriteLog(string message)
    {
        LogEvent.WriteLogEventArgs args = new LogEvent.WriteLogEventArgs(message);
        new LogEvent().OnWriteLog(args);
    }
}

//3. Class where event should be consumed
public class MyClass()
{
    private LogEvent _logEvent;
    public MyClass()
        {
            //Subscribe to event:
            _logEvent = new LogEvent();
            _logEvent.WriteLog += (sender, args) => { DoSomething(args.Message); };
        }

   public void DoSomething(string message)
   { ... }
}

兩個問題:

  • 無論有人是否訂閱,您都在舉報該活動。 請勿這樣做-如果WriteLog為null時調用WriteLog(this, e) 則將獲得NullReferenceException 在C#6中,很容易避免這種情況:

     WriteLog?.Invoke(this, e); 
  • 您要在與引發事件的LogEvent實例不同的LogEvent實例上訂閱該事件。 這比其他任何事情更多的是設計問題-單個日志事件具有訂戶列表是沒有意義的。 取而代之的是,您應該有一個Logger或具有訂閱者的Logger或類似者(通過事件),然后將每個LogEvent傳遞給那些訂閱者。 您將創建一個 Logger ,訂閱它,然后在同一實例上調用WriteLog

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM