You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何实现多参数适配方法 重构仅比较运算符不同的重复代码

解决方案

你这段代码的两个判断逻辑本质是检查A矩形是否完全包含在B矩形内部,仅两次调用时传入的参数顺序、返回值不同,直接提取公共判断方法即可:

public static int IndexOfInnerRectangle(Rectangle r1, Rectangle r2)
{
    // r1在r2内部返回0
    if (IsRectangleInside(r1, r2))
        return 0;
    // r2在r1内部返回1
    if (IsRectangleInside(r2, r1))
        return 1;
    return -1;
}

// 提取的独立公共方法:判断a是否完全包含在b内部
private static bool IsRectangleInside(Rectangle a, Rectangle b)
{
    return a.Left >= b.Left 
        && a.Right <= b.Right 
        && a.Top >= b.Top 
        && a.Bottom <= b.Bottom;
}

如果需要更灵活的通用实现,支持自定义不同比较逻辑,可以用委托参数封装运算符规则,适合后续需要扩展更多判断场景的情况:

public static int IndexOfInnerRectangle(Rectangle r1, Rectangle r2)
{
    if (CheckRectangleCondition(r1, r2, (x, y) => x >= y, (x, y) => x <= y))
        return 0;
    if (CheckRectangleCondition(r1, r2, (x, y) => x <= y, (x, y) => x >= y))
        return 1;
    return -1;
}

// 通用判断方法,支持传入自定义边界比较逻辑
private static bool CheckRectangleCondition(Rectangle a, Rectangle b, 
    Func<int, int, bool> horizontalCompare, 
    Func<int, int, bool> verticalCompare)
{
    return horizontalCompare(a.Left, b.Left)
        && verticalCompare(a.Right, b.Right)
        && horizontalCompare(a.Top, b.Top)
        && verticalCompare(a.Bottom, b.Bottom);
}

两种方案按需选择即可:第一种固定判断方法的写法更简洁易读,适配你当前的场景;第二种带委托参数的实现扩展性更强,新增比较规则时不需要重复写矩形边界判断的模板代码。

内容的提问来源于stack exchange,提问作者tmaline

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 04:09:03