NullReferenceException:未将对象引用设置为对象的实例。使用c#在Asp.net中显示错误

时间:2013-07-21 03:47:12

标签: asp.net nullreferenceexception

Line 24:             if (word.Length<3)

Line 25:             {
Line 26:                 Label1.Visible = true;

Source File: C:\Users\c-tac\Documents\Visual Studio 2010\Projects\telephone\telephone\show.aspx.cs    Line: 24

堆栈追踪:

[NullReferenceException: Object reference not set to an instance of an object.]

2 个答案:

答案 0 :(得分:0)

看起来非常明显,word未设置为实例;换句话说,word为空。

检查以确保word未被使用,除非它被实例化为某种东西,如下所示:

if(word != null)
{
    // Do stuff with word, because you know it actually exists now
}

注意:这称为defensive programming,几乎可以消除代码中的所有NullReferenceException。它还有一个额外的好处,就是在特定对象为空时(例如,应该向用户报告,如果这会导致应用程序结束等),让您考虑应该对代码执行的操作。 / p>

答案 1 :(得分:0)

当您想要使用通常无法使用null值执行迭代的迭代时,会发生NullReferenceException。您应检查代码,如果值为null,请确保在其他内容之前为其分配默认值。或者只是做简单的方法并使用try and catch。

 try
 {
      // do your stuff with word
 }
 catch
 {
      // handle the null exception
 }

虽然基于您的代码null,但意味着您的单词长度为零。所以你也可以这样做。

 if(word != null || word.lenght<3)
 {
      // do your thing
 }