对象引用未设置为对象按钮按下事件的实例 [英] Object reference not set to an instance of an object button press event

查看:120
本文介绍了对象引用未设置为对象按钮按下事件的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到一条错误消息,但我不知道如何解决.这是我的原始代码:

I'm getting an error message and I don't know how to fix it. This is the original code I have:

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);
    }
}

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

The error message is (button press event)

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

Object reference not set to an instance of an object.

为什么会收到此错误消息,我该如何解决?

Why am I getting this error message and how can i fix it?

推荐答案

每次您遇到这样的错误(NullReferenceException)时,您的代码中都会有一些内容设置为null.您必须查看代码并确定:

Every time you get such an error (a NullReferenceException), there is something in your code that is set to null. You have to look at your code and determine:

  1. 在哪一行(用哪种方法)会发生错误?
  2. 该行上的哪些变量是引用类型可空值类型?
    普通值类型(例如,struct,或整数,浮点数,双精度数)不能为null.
  3. 这些变量中,可能可能是null?
  4. 哪些变量可能设置为null?
    例如,方法参数,方法返回的值或as运算符的结果可能导致变量为null .
  1. On which line (in which method) does the error occur?
  2. What variables on that line are reference types or nullable value types?
    Normal value types (e.g. struct, or integers, floats, doubles) cannot be null.
  3. Of those variables, which could possibly be null?
  4. Where are those variables possibly set to null?
    For example, a method argument, a value returned from a method, or the result of the as operator can result in a variable being null.

如果所有这些都不是,则您可能具有(尽管不太可能)引发此异常的方法. .NET基类方法通常不会引发此类异常,并且如果您的代码确实引发了这种异常,则堆栈跟踪应将您带入执行该异常的最深层方法和行.

If none of those is the case, you might have (although unlikely) a method that is throwing this exception. The .NET base class methods generally don't throw such an exception, and if your code does throw it, your stack trace should bring you to the deepest method and line that does that.

这篇关于对象引用未设置为对象按钮按下事件的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆