C#中的多种方法

时间:2013-08-13 01:56:09

标签: c#

我想要很多方法。但是,我不想一遍又一遍地写它。我想要方法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;
    }
}

1 个答案:

答案 0 :(得分:7)

只需制作一个方法,如下:

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