IMO,这一次检查的条件太多了。我会将它们分解,然后以独立的方式处理每个条件,这将使事情更容易调试以及将来阅读/理解。
// Too much going on here; let's refactor.
if (jump == true
&& jumped == 0
&& (Player.Location == new Point(Player.Location.X, Block1.Location.Y - Player.Height)
|| Player.Top == this.Height - Player.Height))
{
//do something...
}
与其创建一个大的 if 语句,不如将条件合并到一个方法中:
// first refactor
private bool IsValidForSomeAction()
{
if(!jump)
{
return false;
}
if(jumped != 0)
{
return false;
}
if(Player.Top == this.Height - Player.Height)
{
return true;
}
if (Player.Location == new Point(Player.Location.X, Block1.Location.Y - Player.Height))
{
return true;
}
return false;
}
在第一个 refator 之后,很明显不需要再为最终的比较创建一个新的 Point:
// second refactor
private bool IsValidForSomeAction()
{
if(!jump)
{
return false;
}
if(jumped != 0)
{
return false;
}
if(Player.Top == this.Height - Player.Height)
{
return true;
}
// only the Y location matters, no need to create a new Point for the comparison.
if (Player.Location.Y == Block1.Location.Y - Player.Height)
{
return true;
}
return false;
}
现在,让我们专注于真正重要的事情:if (Player.Location.Y == Block1.Location.Y - Player.Height)。条件归结为 Block 的 Y 位置和 Player 的高度之间的差异。
假设可能有 10、20、50 或 100 多个要比较的块,则创建一个包含所有块的集合的私有字段。
// override the onload event and find all the picture boxes:
private readonly List<PictureBox> _boxes = new List<PictureBox>();
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
_boxes.AddRange(this.Controls.OfType<PictureBox>()
}
_boxes 字段随后可用于最终验证:
// third refactor
private bool IsValidForSomeAction()
{
if(!jump)
{
return false;
}
if(jumped != 0)
{
return false;
}
if(Player.Top == this.Height - Player.Height)
{
return true;
}
// only the Y location matters, no need to create a new Point for the comparison.
if(_boxes.Any(x => x.Location.Y - Player.Height == Player.Location.Y)
{
return true;
}
return false;
}