简体   繁体   中英

Error: Object reference not set to an instance of an object

I'm develop an application using ASP.NET in c#, and I hit the following error:

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

and this is my code fragment:

Match matchNew = Regex.Match(parts[0].ToString(), @"([0]\.\d*)|[1]\.[0]$", RegexOptions.IgnoreCase);

It was testing in my local the code was perfectly fine, but it hit this error when moved the same code to my virtual environment.

I'm guessing maybe it is due to the dot net framework in my virtual environment.

Please help and thank you in advanced.

Most likely parts[0] is null. This error is equivalent to a NullPointerException in Java.

Try setting a local variable to parts[0].ToString(); on the previous line, and see if the exception is thrown from that line instead.

I recommend only performing your match if you have something to perform it on:

if(parts[0] != null){
    Match matchNew = Regex.Match(parts[0].ToString(), @"([0]\.\d*)|[1]\.[0]$", RegexOptions.IgnoreCase);
}

From the exception you're getting, it looks like either parts or parts[0] is null.

Perhaps consider introducing a variable for parts to see if that is null, and if so, handle either with a default value or display an error to the user, or throw an exception if that is appropriate in your situation.

object part = parts[0];
if (part == null)
{
    // part is null, either handle with default value or error.
}

Match matchNew = ...;

Most likely it is your array "parts" if its length is 0 then it will fail. Make sure to test it's length first.

replace the code by this :

if(parts != null && parts.Length>0)
{    

    if(parts[0] != null)
    {
       Match matchNew = Regex.Match(parts[0].ToString(), @"([0]\.\d*)|[1]\.[0]$", RegexOptions.IgnoreCase);
    }
}

and it would work fine. The array parts appears to be null in your case. But ideally you should also check if the array has elements and if the element in question is not null before you try to convert it to a string value.

看来您的数组"parts"没有元素,因此parts[0]为null,并且由于.ToString()而发生异常,因为null无法转换为字符串。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM