c# - C#中的多个方法

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

最佳答案

只做一个方法,像这样:

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/

相关文章:

c# - 如何安排数据库任务?

c# - 调用更改组件(标签)的父类(super class)函数

c# - winmd 找不到 Newtonsoft.Json.dll 文件

c# - 如何将递归结构编码为 c sharp?

c# - 始终运行的 Windows 程序

c# - 通过远程桌面连接时出现 IValueConverter NullReferenceException

c# - if 循环和指标内的代码行数更多

C# 通用约束未按预期工作

c# - 等待阻塞集合(队列)在 C# 中减小大小

c# - 是否可以有一个也适用于其他项目的扩展类?