简体   繁体   English

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

[英]c# not all code paths return a value error in simple method

Simple program for class to count words and getting the error above and it driving me mad. 类的简单程序可以计算单词并获得上面的错误,这让我很生气。

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

If the string will be empty the return command will not be executed.. 如果字符串为空,则不会执行return命令。

Use this instead: 请改用:

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

Your code is returning from inside of foreach loop, if the parameter passed is null , you will get an exception, if it is an empty string, execution will not enter the loop hence the error. 你的代码是从foreach循环内部返回的,如果传递的参数为null ,你将得到一个异常,如果它是一个空字符串,执行将不会进入循环因此错误。

Your current method is also incorrect logically since it will return after first iteration, possibly giving you incorrect result. 您当前的方法在逻辑上也是错误的,因为它将在第一次迭代后返回,可能会给您不正确的结果。 Your return statement should be outside of foreach loop 你的return语句应该在foreach循环之外

Your method is declared as int, which means it MUST return a value. 您的方法声明为int,这意味着它必须返回一个值。 The compiler is complaining that this is not guaranteed to be the case. 编译器抱怨说不能保证这种情况。 Specifically if the string is empty your foreach is not entered and no return statement is executed. 特别是如果字符串为空,则不会输入foreach,也不会执行return语句。

On another note, having a forced return on the first iteration makes the foreach pointless. 另一方面,在第一次迭代中强制返回使得foreach毫无意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM