C#:并非所有代码路径都返回值和无法访问的代码?

Kar*_*tik 2 c# compiler-errors

嘿所以我有这个代码,我检查一下玩家是否可以从他们的库存中删除'项目'.'Inventory'是一个Sorted Dictionary(Item,int)(subquestion:我需要一个排序的字典,以便能够访问索引号中的项目吗?),Item是一个类.

     public bool CanRemoveFromItemInventory(string item)
    {
        bool temp = false;
        if (ItemInventory.Count() <= 0)
        {
            return false;
        }
        else if (ItemInventory.Count() > 0)
        {
            for (int b = 0; b < ItemInventory.Count(); b++)
            {
                Item i = ItemInventory.Keys.ElementAt(b);
                if (i.GetName().Equals(item) && ItemInventory[i] >= 1)
                {
                    temp = true;
                }
                else
                {
                    temp = false;
                }

                if (!temp)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }
        else
        {
            return temp;

         }
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 6

编译器不会尝试理解逻辑 - 它只是应用规则.就它而言,for循环可能执行次,因此中间块缺少返回值:

    else if (ItemInventory.Count() > 0)
    {
        for (int b = 0; b < ItemInventory.Count(); b++)
        {
              // ... this always returns something
        }
        // BUT STILL NEED TO EITHER RETURN OR THROW HERE
    }
Run Code Online (Sandbox Code Playgroud)

事实上,这是正确的 - 因为一个邪恶的不满情绪可以编写一个Count()方法,每次调用返回不同的值(或呈现一个不那么邪恶的情况 - 线程竞赛/数据突变).

也许这里最简单的"修复"是改变:

    else
    {
        return temp;
    }
Run Code Online (Sandbox Code Playgroud)

简单地说:

    return temp;
Run Code Online (Sandbox Code Playgroud)

那么它将适用于所有分支机构.