C#...并非所有代码路径都返回一个值

igg*_*012 -1 c# accessor

我正在尝试使用属性及其各自的访问器创建一个Collection.

这是我的代码:

class SongCollection : List<Song>
{
    private string playedCount;
    private int totalLength;

    public string PlayedCount
    {
        get
        {
            foreach (Song s in this)
            {
                if (s.TimesPlayed > 0)
                {
                    return s.ToString();
                }
            }
        }
    }


    public int TotalLength
    {
        get
        {
            foreach (Song s in this)
            {
                int total = 0;
                total += s.LengthInSeconds;
            }
            return total;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在"获取"点收到错误.它告诉我并非所有代码路径都返回一个值......这究竟是什么意思,我错过了什么?

Ada*_*son 6

首先,你获得该消息的原因是如果this为空,那么foreach块中的代码(所需return语句所在的位置)将永远不会被执行.

但是,当您声明变量,设置其值,然后在块内返回时,您的TotalLength()函数将始终返回第一个的长度.相反,你需要做这样的事情:Songforeach

int totalLength = 0;

foreach(Song s in this)
{
    total += s.LengthInSeconds;
}

return totalLength;
Run Code Online (Sandbox Code Playgroud)

您的PlayedCount函数遇到类似问题(如果集合为空或者不包含其TimesPlayed属性大于0的元素,那么它将无法返回值),因此根据您的注释判断,您可以这样写:

public int PlayedCount()
{
    int total = 0;

    foreach(Song s in this)
    {
        if (s.TimesPlayed > 0)
        {
            total++;
        }
    }

    return total;
}
Run Code Online (Sandbox Code Playgroud)