2

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);
       }
    }

selectedstory.Slugの値がnullであることがわかっているため、if条件を使用してチェックしましたが、if条件ですぐにスローされます。

誰かがチェックする正しい方法を教えてもらえますか?

4

4 に答える 4

9

null参照でメソッドを呼び出すことはできません。を取り出します.Trim()

于 2012-05-10T03:21:55.737 に答える
6
if((selectedstory.Slug).Trim()!=null)

最初に文字列のメソッドを呼び出し、次にTrim()nullをチェックします。これは失敗している部分です。nullオブジェクトでインスタンスメソッドを呼び出そうとしています。

あなたが欲しいものはこのようなものです:

if ( selectedstory != null && string.IsNullOrEmpty(selectedstory.Slug) )
于 2012-05-10T03:23:10.793 に答える
6

これを試してください:

if (!string.IsNullOrWhiteSpace(selectedstory.Slug))

これにより、チェックしているプロパティでTrimを呼び出す必要がなくなります。

于 2012-05-10T03:23:42.540 に答える
0

これが私がついに思いついたものです

    try
        {

            if (!string.IsNullOrWhiteSpace(selectedstory.Slug))
            {

                if (File.Exists(pathToImage))
                {
                    string SlugName = selectedstory.Slug;
                    if (pathToImage.Contains(SlugName))
                    {

                    }
                    else
                    {
                        this.dialog.ShowError("Image file name is not same as Slug name", null);
                    }
                }
                else
                {
                    this.dialog.ShowError("Image file does not exist at the specified location", null);
                }

            }
          }
        catch (Exception ex)
        {
            this.dialog.ShowError("Slug is Empty,please enter the Slug name", null);

        }
    }
于 2012-05-10T04:33:35.290 に答える