关于C#:对象引用未设置为对象的实例


Object reference not set to an instance of an object.

本问题已经有最佳答案,请猛点这里访问。

当我运行程序时,我一直收到这个错误。

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.

1
2
3
4
5
Source Error:

Line with error:

Line 156:        if (strSearch =="" || strSearch.Trim().Length == 0)

正确的书写方式是什么?


正确的方式是:在.NET 4.0

1
if (String.IsNullOrWhiteSpace(strSearch))

在上面的方法使用的是String.IsNullOrWhiteSpace等价:

1
2
if (strSearch == null || strSearch == String.Empty || strSearch.Trim().Length == 0)
// String.Empty is the same as""

Reference for IsNullOrWhiteSpace method

http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx

Indicates whether a specified string is Nothing, empty, or consists
only of white-space characters.

在早期的版本,你可以做这样的东西:

1
if (String.IsNullOrEmpty(strSearch) || strSearch.Trim().Length == 0)

在上面的方法使用的是String.IsNullOrEmpty等价:

1
if (strSearch == null || strSearch == String.Empty)

这意味着你仍然需要检查你的"iswhitespace"案例与.Trim().Length == 0AS用的例子。

Reference for IsNullOrEmpty method

http://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx

Indicates whether the specified string is Nothing or an Empty string.

解释:

你需要确保strSearch(或任何物变为那个)是不是在你nulldereference它使用点阵字符(.)。在你或你需要做的strSearch.SomeMethod()strSearch.SomePropertystrSearch != null检查这。

在你的例子,你想确保你有一个字符串值,这意味着你要确保字符串:

  • 是不是零
  • 一个空字符串(String.Empty/ "")
  • 是不是只是空白。

在上面的情况,你必须把"零is it?"案例第一,所以它不会去检查其他情况下(和错误),当字符串是null


网:所有版本。

1
if (String.IsNullOrEmpty(strSearch) || strSearch.Trim().Length == 0)

NET 4.0或之后:

1
if (String.IsNullOrWhiteSpace(strSearch))


我知道这是张贴大约一年前,但这是用户未来的参考。

我是在类似的问题。在我的案例(我想信做的尝试,请让我知道如果你想更多的细节),我试图检查是否是空字符串或不(字符串是主题,电子邮件)。它总是返回相同的错误消息不知道我做的。我知道我会做它,但它仍然改变了相同的错误消息。那就在我dawned我检查,如果主体(字符串)的电子邮件(例如/对象),电子邮件(如果可能)A零已经在第一位。我怎么检查a在电子邮件的主题,如果电子邮件已经为零,一检查,如果电子邮件是空的,它会好的。

在检查的主题(字符串),用于isnullorwhitespace(I)isnullorempty()方法。

1
2
3
4
5
6
7
8
if (email == null)
{    
     break;    
}
else
{    
     // your code here    
}


在本案例strsearch是零(不就是空的)。

尝试使用

String.IsNullOrEmpty(strSearch)

如果你想确定如果字符串没有任何内容。


我想mattmitchell extend的回答说,你可以通过这个功能来创建扩展方法:

1
2
3
public static IsEmptyOrWhitespace(this string value) {
    return String.IsEmptyOrWhitespace(value);
}

这使得它可能的调用:

1
2
3
string strValue;
if (strValue.IsEmptyOrWhitespace())
     // do stuff

我本是一个焊料的String清洁比静态函数调用,而nullreference安静是安全的!