我有一个 StatusChanged 事件,该事件由我的对象在其状态更改时引发 - 但是,应用程序需要根据新状态执行其他操作。
例如,如果新状态为断开连接,则它必须更新状态栏文本并发送电子邮件通知。
因此,我想创建一个具有可能状态(已连接、已断开、接收数据、发送数据等)的枚举,并在引发事件时将其与事件的 EventArgs 参数一起发送(见下文)
定义对象:
class ModemComm
{
public event CommanderEventHandler ModemCommEvent;
public delegate void CommanderEventHandler(object source, ModemCommEventArgs e);
public void Connect()
{
ModemCommEvent(this, new ModemCommEventArgs ModemCommEventArgs.eModemCommEvent.Connected));
}
}
定义新的 EventArgs 参数:
public class ModemCommEventArgs : EventArgs{
public enum eModemCommEvent
{
Idle,
Connected,
Disconnected,
SendingData,
ReceivingData
}
public eModemCommEvent eventType { get; set; }
public string eventMessage { get; set; }
public ModemCommEventArgs(eModemCommEvent eventType, string eventMessage)
{
this.eventMessage = eventMessage;
this.eventType = eventType;
}
}
然后我为应用程序中的事件创建一个处理程序:
ModemComm comm = new ModemComm();
comm.ModemCommEvent += OnModemCommEvent;
和
private void OnModemCommEvent(object source, ModemCommEventArgs e)
{
}
问题是,当对象尝试引发事件时,我收到“对象引用未设置为对象的实例”错误。希望有人能用 n00b 术语解释为什么以及如何解决它:)