c#并非所有代码路径都以简单方法返回值错误

Mos*_*sep 2 c#

类的简单程序可以计算单词并获得上面的错误,这让我很生气.

int words; //variable to hold word count.

//WordCount methos will count the spaces and punciation.
private int WordCount(string str)
{
    int words = 0; //the number of words counted

    //count the white spaces and punctuation.
    foreach (char ch in str)
    {
        if (char.IsWhiteSpace(ch))
        {
            words++;
        }
        if (char.IsPunctuation(ch))
        {
            words++;
        }

        //return number of words
        return words;
    }
}
Run Code Online (Sandbox Code Playgroud)

Tom*_*zan 8

如果字符串为空,则不会执行return命令.

请改用:

//WordCount methos will count the spaces and punciation.
private int WordCount(string str)
{
    int words = 0; //the number of words counted

    //count the white spaces and punctuation.
    foreach (char ch in str)
    {
        if (char.IsWhiteSpace(ch))
        {
            words++;
        }
        if (char.IsPunctuation(ch))
        {
            words++;
        }
   }

   //return number of words
   return words;
}
Run Code Online (Sandbox Code Playgroud)

  • 它也不会检查除第一个之外的任何字符. (2认同)