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

Mis*_*Dei 0 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.");
            }


        }
    }
Run Code Online (Sandbox Code Playgroud)

Mit*_*dir 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.");
Run Code Online (Sandbox Code Playgroud)

  • @DidierGhys:不一样! (3认同)
  • @DidierGhys这就是为什么你只在最后扔掉"找不到它"的原因.为什么人们贬低这个? (2认同)