为什么这个块会抛出错误
本文关键字:出错 错误 为什么 | 更新日期: 2023-09-27 18:21:47
"并非所有代码路径都返回值"
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.");
}
}
}
将代码更改为:
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.");
如果_BallList
为空,则永远不会进入循环,因此该方法不会返回任何
如果_BallList为空,则不返回任何内容。