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

Rect.Contains方法边界点判定偶现异常问题求助

偶现Rect.Contains(Point)导致序列为空的排查与解决

可能的触发原因

  • 浮点数精度偏差:尽管理论上第一个点必然落在矩形范围内,但double类型的浮点数运算(如points[0].Y - groupSize)可能产生精度损失,导致矩形边界值出现微小偏移,使得Contains方法误判第一个点不在范围内。尤其当坐标值本身较大时,浮点数的相对精度下降,这种偏差更容易触发。
  • 多线程并发修改:如果points集合同时被其他线程修改(例如循环执行过程中,有线程移除了第一个元素),那么执行Where筛选时,原第一个点已不在集合内,会导致筛选结果为空。
  • Rect构造参数的隐性问题:虽然代码构造Rect的参数顺序(左、上、宽、高)符合定义,但极端情况下,超大数值的组合可能引发意想不到的边界计算偏差(概率极低,但偶现问题需考虑)。

针对性解决方案

1. 强制包含第一个点,避免依赖Contains判断

既然逻辑上第一个点必须属于当前组,可直接将其纳入筛选范围,从根源避免序列为空:

var firstPoint = points[0];
double top = points
    .Where(o => o.Equals(firstPoint) || searchBound.Contains(o))
    .Min(o => o.Y);

2. 引入容差值处理浮点数精度

添加极小的容差值,抵消浮点数运算的精度偏差:

const double Epsilon = 1e-9;

bool IsPointInRect(Point point, Rect rect)
{
    return point.X >= rect.Left - Epsilon
        && point.X <= rect.Right + Epsilon
        && point.Y >= rect.Top - Epsilon
        && point.Y <= rect.Bottom + Epsilon;
}

// 使用自定义判断替换原Contains
double top = points
    .Where(o => IsPointInRect(o, searchBound))
    .Min(o => o.Y);

3. 保障集合访问的线程安全

若存在多线程修改points的场景,需加锁保护集合操作:

private readonly object _pointsLock = new object();

while (true)
{
    Point firstPoint;
    lock (_pointsLock)
    {
        if (!points.Any()) break;
        firstPoint = points[0];
    }

    double left = firstPoint.X;
    Rect searchBound = new Rect(left, firstPoint.Y - groupSize, groupSize, 2.0 * groupSize);

    lock (_pointsLock)
    {
        double top = points
            .Where(o => searchBound.Contains(o))
            .Min(o => o.Y);
        
        // 后续分组处理逻辑
    }
}

4. 添加异常日志辅助排查

针对偶现问题,在异常处记录关键数据,方便后续定位:

try
{
    double top = points.Where(o => searchBound.Contains(o)).Min(o => o.Y);
}
catch (InvalidOperationException ex)
{
    // 记录日志:firstPoint.X/Y、searchBound.Left/Top/Right/Bottom、points.Count等
    // 示例日志内容:$"Empty sequence! FirstPoint: ({firstPoint.X}, {firstPoint.Y}), SearchBound: L={searchBound.Left}, T={searchBound.Top}, R={searchBound.Right}, B={searchBound.Bottom}, PointsCount={points.Count}"
    throw;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 23:05:16