为什么if条件不检查空值

Ush*_*her 2 .net c# string

我试图检查我的var中的null,但它抛出"对象引用未设置为对象的实例".

 private void GenerateImage()
    {
        //Webster.Client.Modules.Metadata.Helper test = new Webster.Client.Modules.Metadata.Helper();
         var selectedstory = Webster.Client.Modules.Metadata.Helper.SelectedStoryItem;

        if((selectedstory.Slug).Trim()!=null)
        {
         //if (!string.IsNullOrEmpty(selectedstory.Slug))
       //{

           if (File.Exists(pathToImage))
           {
              }
           else
           {
               this.dialog.ShowError("Image file does not exist at the specified location", null);
           }
       }
       else
       {
           this.dialog.ShowError("Slug is Empty,please enter the Slug name", null);
       }
    }
Run Code Online (Sandbox Code Playgroud)

我知道selectedstory.Slug有空值,这就是为什么我用if条件来检查,但是它在if条件下正好扔了.

有人可以建议检查什么是正确的方法.

Joe*_*ite 9

您无法在空引用上调用方法.取出来.Trim().


Mua*_*Dib 6

if((selectedstory.Slug).Trim()!=null)
Run Code Online (Sandbox Code Playgroud)

将首先Trim()在字符串上调用该方法,然后检查null.这是失败的部分:您正在尝试在null对象上调用实例方法.

你想要的是这样的:

if ( selectedstory != null && string.IsNullOrEmpty(selectedstory.Slug) )
Run Code Online (Sandbox Code Playgroud)


McG*_*gle 6

试试这个:

if (!string.IsNullOrWhiteSpace(selectedstory.Slug))
Run Code Online (Sandbox Code Playgroud)

这样就无需在您正在检查的属性上调用Trim.

  • 应该注意的是,IsNullOrWhiteSpace仅在.net 4及更高版本中可用 (4认同)
  • 使用`IsNullOrWhiteSpace`的+1,不需要`Trim`方法调用 (3认同)