发射事件时出现NullReferenceException

时间:2011-01-12 19:28:16

标签: c# nullreferenceexception

问题是:我得到一个NullReferenceException,但我似乎无法找出原因。 (我刚开始使用C#),并为微软的孩子们阅读了C#。它解释了很多,但我不明白。

但是我没有得到那些将异常抛到脑后的代码。

代码是:

using System;  
using System.Collections.Generic;  
using System.Linq; using System.Text;  
using System.IO.Ports;  
using PlugwiseLib.BLL.BC;  
using plugwiseLib.BLL.BPC;  
using System.Text.RegularExpressions;  

using System.Threading;  
using System.IO;  
using PlugwiseLib.BLL.BPC;
using PlugwiseLib.UTIL;  
 namespace PlugwiseLib {  
       public class plugwiseControl  
     {  
         private SerialPort port;  
         private PlugwiseActions currentAction;  
         public delegate void PlugwiseDataReceivedEvent(object
 sender, System.EventArgs e,
 List<PlugwiseMessage> data);  
         public event PlugwiseDataReceivedEvent
 DataReceived;  

    private PlugwiseReader reader;

    /// <summary>
    /// Constructor for the Plugwise Control class
    /// </summary>
    /// <param name="serialPort">The serial port name that the plugwise stick takes</param>
    public plugwiseControl(string serialPort)
    {
        try
        {
            port = new SerialPort(serialPort);
            port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

            port.BaudRate = 115200;
            currentAction = PlugwiseActions.None;
            reader = new PlugwiseReader();
        }
        catch (Exception e)
        {
            throw new Exception("Could not connect to plug.");
        }
    }

    /// <summary>
    /// This is the method that sends a command to the plugwise plugs.
    /// </summary>
    /// <param name="mac">The mac adress of the plug that needs to perform the action</param>
    /// <param name="action">The action that has to be performed</param>
    public void Action(string mac,PlugwiseActions action)
    {
        try
        {

            string message = "";
            switch (action)
            {
                case PlugwiseActions.On:
                    currentAction = PlugwiseActions.On;
                    message = PlugwiseSerialPortFactory.Create(PlugwiseSerialPortRequest.on,mac);


                    break;
                case PlugwiseActions.Off:
                    currentAction = PlugwiseActions.Off;
                    message = PlugwiseSerialPortFactory.Create(PlugwiseSerialPortRequest.off, mac);


                    break;
                case PlugwiseActions.Status:

                    currentAction = PlugwiseActions.Status;
                    message = PlugwiseSerialPortFactory.Create(PlugwiseSerialPortRequest.status, mac);

                    break;
                case PlugwiseActions.Calibration:
                    currentAction = PlugwiseActions.Calibration;
                    message = PlugwiseSerialPortFactory.Create(PlugwiseSerialPortRequest.calibration, mac);


                    break;
                case PlugwiseActions.powerinfo:
                    currentAction = PlugwiseActions.powerinfo;
                    message = PlugwiseSerialPortFactory.Create(PlugwiseSerialPortRequest.powerinfo,mac);

                    break;
                case PlugwiseActions.history:
                    message = "";
                    break;
            }
            if (message.Length > 0)
            {
                port.WriteLine(message);
                Thread.Sleep(10);
            }

        }
        catch (Exception e)
        {

            throw e;
        }
    }
    /// <summary>
    /// This is the method that sends a command to the plugwise plugs that retrieves the history power information
    /// </summary>
    /// <param name="mac">The mac adress of the plug that needs to perform the action</param>
    /// <param name="logId">The id of the history message that has to be retrieved</param>
    /// <param name="action">The action that has to be performed this MUST be history</param>
    public void Action(string mac,int logId,PlugwiseActions action)
    {
        string message = "";
        switch(action)
        {
            case PlugwiseActions.history:
             currentAction = PlugwiseActions.history;
             message = PlugwiseSerialPortFactory.Create(PlugwiseSerialPortRequest.history, MessageHelper.ConvertIntToPlugwiseLogHex(logId), mac);
         break;
        }

        if (message.Length > 0)
        {
            port.WriteLine(message);
            Thread.Sleep(10);
        }
    }

    private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {// Event for receiving data

        string txt = port.ReadExisting();
        List<PlugwiseMessage> msg = reader.Read(Regex.Split(txt, "\r\n"));
        DataReceived(sender, new System.EventArgs(), msg);


    }

    /// <summary>
    /// This method Opens the connection to the serial port
    /// </summary>
    public void Open()
    {
        try
        {
            if (!port.IsOpen)
            {
                port.Open();
            }
        }
        catch (System.IO.IOException ex)
        {
            throw ex;
        }
    }

    /// <summary>
    /// This method closes the connection to the serial port
    /// </summary>
    public void Close()
    {
        try
        {
            if (port.IsOpen)
            {
                port.Close();
            }
            Thread.Sleep(5);
        }
        catch (IOException ex)
        {
            throw ex;
        }
    }
  }
}

我在这篇文章中得到了例外(在Visual C#2008快递中)

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{// Event for receiving data

    string txt = port.ReadExisting();
    List<PlugwiseMessage> msg = reader.Read(Regex.Split(txt, "\r\n"));
    DataReceived(sender, new System.EventArgs(), msg);

alt text

我检查了'msg',但到目前为止我已经看到了有效的数据。 所以我不知道为什么我会得到例外。

3 个答案:

答案 0 :(得分:3)

您有plugwiseControl.DataReceived个活动的订阅者吗?提出事件的常用方法是

var handler = DataReceived;
if(handler != null) handler(sender, EventArgs.Empty, msg);

答案 1 :(得分:2)

我认为调用方法没有初始化DataReceived事件。

答案 2 :(得分:1)

在.NET中,如果你举起一个事件而且该事件没有注册的监听器(你的事件没有做什么,你在构造函数的try {}块的第二行中对你的端口的DataReceived事件做了什么) ,它显示为null,并引发该异常。在您的监视列表屏幕截图中,DataReceived为null,这让我觉得这是问题所在。所以:

if (DataReceived != null)
  DataReceived(...arguments here...);