C#中的多个方法

本文关键字:方法 | 更新日期: 2023-09-27 18:27:36

我想要很多方法。然而,我不想一遍又一遍地写它。我想要方法bBIntersectsB1,bBIntersectsB2。。。,bB接口B9、bB接口B10。在每种方法中,唯一的变化是代替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;
    }
}

C#中的多个方法

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

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