引发自定义事件时出错
Error when raising custom event
我有一个 class 可以写日志。 class 需要引发一个事件(在下面未说明的特定情况下),该事件将由 class 消耗以对其做出反应。我有下面的代码,但是当我尝试引发事件时,我在行中收到一个错误,如指示的那样,
Object reference not set to an instance of an object
知道我错过了什么吗?
//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
为空时调用 WriteLog(this, e)
,你 将 得到 NullReferenceException
。在 C# 6 中很容易避免这种情况:
WriteLog?.Invoke(this, e);
您在与引发事件的实例不同的 LogEvent
实例上订阅事件。这更像是一个设计问题——单个日志事件拥有订阅者列表是没有意义的。相反,您应该有一个 Logger
或类似的订阅者(通过事件),然后将每个 LogEvent
传递给这些订阅者。您将创建 one Logger
,订阅它,然后在同一实例上调用 WriteLog
。
我有一个 class 可以写日志。 class 需要引发一个事件(在下面未说明的特定情况下),该事件将由 class 消耗以对其做出反应。我有下面的代码,但是当我尝试引发事件时,我在行中收到一个错误,如指示的那样,
Object reference not set to an instance of an object
知道我错过了什么吗?
//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
为空时调用WriteLog(this, e)
,你 将 得到NullReferenceException
。在 C# 6 中很容易避免这种情况:WriteLog?.Invoke(this, e);
您在与引发事件的实例不同的
LogEvent
实例上订阅事件。这更像是一个设计问题——单个日志事件拥有订阅者列表是没有意义的。相反,您应该有一个Logger
或类似的订阅者(通过事件),然后将每个LogEvent
传递给这些订阅者。您将创建 oneLogger
,订阅它,然后在同一实例上调用WriteLog
。