问题
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?
回答1:
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:
- On which line (in which method) does the error occur?
- What variables on that line are reference types or nullable value types?
Normal value types (e.g.struct
, or integers, floats, doubles) cannot benull
. - Of those variables, which could possibly be
null
? - Where are those variables possibly set to
null
?
For example, a method argument, a value returned from a method, or the result of theas
operator can result in a variable beingnull
.
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.
来源:https://stackoverflow.com/questions/15513930/object-reference-not-set-to-an-instance-of-an-object-button-press-event