我想有很多方法。但是,我不想一遍又一遍地写。我想要方法 bBIntersectsB1、bBIntersectsB2、...、bBIntersectsB9、bBIntersectsB10。在每个方法中,唯一的变化是 blueBallRect1,我想要 blueBallRect2,...,blueBallRect9,blueBallRect10。
public bool bBIntersectsB1(Rect barTopRect, Rect barBottomRect, Rect blueBallRect1)
{
barTopRect.Intersect(blueBallRect1);
barBottomRect.Intersect(blueBallRect1);
if (barTopRect.IsEmpty && barBottomRect.IsEmpty)
{
return false;
}
else
{
return true;
}
}
最佳答案
只做一个方法,像这样:
public bool DoesIntersect(Rect topRect, Rect bottomRect, Rect ballRect)
{
topRect.Intersect(ballRect);
bottomRect.Intersect(ballRect);
if (topRect.IsEmpty && bottomRect.IsEmpty)
{
return false;
}
else
{
return true;
}
}
然后只需调用 DoesIntersect
,如下所示:
var doesBall1Intersect = DoesIntersect(topRect, bottomRect, blueBallRect1);
var doesBall2Intersect = DoesIntersect(topRect, bottomRect, blueBallRect2);
var doesBall3Intersect = DoesIntersect(topRect, bottomRect, blueBallRect3);
var doesBall4Intersect = DoesIntersect(topRect, bottomRect, blueBallRect4);
var doesBall5Intersect = DoesIntersect(topRect, bottomRect, blueBallRect5);
var doesBall6Intersect = DoesIntersect(topRect, bottomRect, blueBallRect6);
var doesBall7Intersect = DoesIntersect(topRect, bottomRect, blueBallRect7);
var doesBall8Intersect = DoesIntersect(topRect, bottomRect, blueBallRect8);
var doesBall9Intersect = DoesIntersect(topRect, bottomRect, blueBallRect9);
只要替换 blueBallRectX
就可以重复多次。
您还可以遍历 BlueBallRect
对象列表并将每个对象传递给 DoesIntersect
方法,如下所示:
List<BlueBallRect> listOfBlueBallRect = new List<BlueBallRect>();
listOfBlueBallRect = SomeMethodThatGetsListOfBlueBallRect;
foreach(BlueBallRect ball in listOfBlueBallRect)
{
if(DoesIntersect(topRect, bottomRect, ball))
{
// Do something here, because they intersect
}
else
{
// Do something else here, because they do not intersect
}
}
关于c# - C#中的多个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18199478/