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

位移操作触发System.OverflowException:ushort存入ArraySegment<byte>遇问题

问题分析与解决方案

你的代码抛出System.OverflowException的核心原因是使用了in修饰符修饰ArraySegment<byte>参数——in会将值类型参数标记为只读,虽然ArraySegment的索引器最终操作的是底层数组,但这种只读约束可能引发意外的运行时异常(你的堆栈跟踪可能误指向了高字节计算行,实际问题出在索引赋值环节)。此外,原代码中&255是多余的,ushort右移8位后结果必然在byte的取值范围内(0~255),无需额外掩码。

修改后的代码

public static void SetUshort(ushort value, int i1, int i2, ArraySegment<byte> arr)
{
     // 直接获取高字节,无需&255
     arr[i1] = (byte)(value >> 8);
     arr[i2] = (byte)value;
}

public static ushort GetUshort(int i1, int i2, ArraySegment<byte> arr)
{
    return (ushort)(arr[i1] << 8 | arr[i2]);
}

验证说明

移除in修饰符后,参数不再受只读约束,索引赋值操作可以正常修改底层数组。修改后的代码可以通过所有测试用例,包括ushort.MaxValue的场景,同时保持了你想要的简洁索引式实现。

内容的提问来源于stack exchange,提问作者Shiv-iwnl

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 13:03:11