对象引用未设置为对象按钮按下事件的实例

时间:2013-03-20 01:54:41

标签: c# winsockets

我收到错误消息,我不知道如何修复它。这是我的原始代码:

private void SendMessage(Command cmd, EndPoint sendToEP)
{
    try
    {
        //Create the message to send.
        Data msgToSend = new Data();

        //msgToSend.strName = txtName.Text;   //Name of the user.
        msgToSend.cmdCommand = cmd;         //Message to send.
        msgToSend.vocoder = vocoder;        //Vocoder to be used.

        byte[] message = msgToSend.ToByte();

        //Send the message asynchronously.
        clientSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, sendToEP, new AsyncCallback(OnSend), null);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "UniProject-SendMessage ()", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

错误信息是(按钮按下事件)

  

对象引用未设置为对象的实例。

为什么我收到此错误消息以及如何解决?

1 个答案:

答案 0 :(得分:3)

每次出现此类错误(NullReferenceException)时,代码中的某些内容都会设置为null。你必须查看你的代码并确定:

  1. 错误发生在哪一行(在哪种方法中)?
  2. 该行上的哪些变量是引用类型可空值类型?正常值类型(例如struct或整数,浮点数,双打)不能是null
  3. 那些可能可能null的变量?
  4. 这些变量可能设置为null的位置?
    例如,方法参数,从方法返回的值或as运算符的结果可以导致变量是null
  5. 如果不是这种情况,您可能(尽管不太可能)抛出此异常的方法。 .NET基类方法通常不会抛出这样的异常,如果你的代码抛出它,你的堆栈跟踪应该会带你到最深的方法和行。