为什么这个块会抛出错误?

时间:2012-01-26 20:24:17

标签: c#

“并非所有代码路径都返回值”

 public BallData GetBall(String Name)
    { 
        //Check each item in the list for the name.
        foreach (BallData Item in _BallList)
        {
            //If the name matches, return the item to the caller and exit the loop.
            if (Item.Name == Name)
            {
                return Item;
            }
            else
            {
                // Otherwise, throw an exception to indicate that the ball wasn't found.
                throw new KeyNotFoundException("The ball name doesn't exist.");
            }


        }
    }

3 个答案:

答案 0 :(得分:5)

将您的代码更改为:

 foreach (BallData Item in _BallList)
 {
            //If the name matches, return the item to the caller and exit the loop.
            if (Item.Name == Name)
            {
                return Item;
            }

  }
  throw new KeyNotFoundException("The ball name doesn't exist.");

答案 1 :(得分:3)

如果_BallList为空,您将永远不会进入循环,因此该方法不会返回任何内容

答案 2 :(得分:1)

如果_BallList为空,则不返回任何内容。