1

I want to have many methods. However, I do not want to write it over and over again. I want to have methods bBIntersectsB1, bBIntersectsB2, ..., bBIntersectsB9, bBIntersectsB10. And in every methods, the only change is instead of blueBallRect1, I want 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;
    }
}
4

1 回答 1

7

Just make one method, like this:

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;
    }
}

And then just call DoesIntersect, like this:

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);

And on and on as many times as you want just substituting the blueBallRectX.

You can also loop through a list of BlueBallRect objects and pass each one to the DoesIntersect method, like this:

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
    }
}
于 2013-08-13T02:03:13.653 回答