C#并非所有代码路径都在简单方法中返回值错误

标签 c#

简单的类(class)程序来计算单词并出现上述错误,这让我抓狂。

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

最佳答案

如果字符串为空,返回命令将不会被执行..

改用这个:

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

关于C#并非所有代码路径都在简单方法中返回值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19962513/

相关文章:

c# - 使用 ICollectionView 过滤 ObservableCollection

c# - 有没有办法确定 C# 4.0 中接口(interface)/委托(delegate)的方差?

c# - 从 ServiceStack 服务中清理 JSON

c# - 查找每个键具有最大值的行

c# - 将代码从 .aspx 文件移动到 .cs 文件,没有任何区别

c# - 随机矩阵的最佳类型 - 需要来源

c# - XNA中如何正确卸载图形资源?

java无法解析unicode '\x00a0'

c# - 如何以编程方式禁用网络摄像头二极管

c# - java 服务器 <-> c# + javascript + java + * 客户端