C#如何跨方法传递数组?调用出现INF错误解决方案
易货交易系统乐器价格计算问题修复
问题原因
- 作用域不匹配:
CalInstrumentCost中定义的priv是方法局部变量,生命周期仅在方法执行期间,外部方法无法直接访问 - 全局变量使用错误:ASP.NET WebMethod是无状态的并发处理模型,全局变量会被不同请求交叉覆盖,未初始化时数组元素默认值为0,直接做分母就会触发除以零,返回INF无穷值,同时还会出现不同请求间数据串扰的严重bug
- 代码冗余:两个接口重复实现了JSON文件读取、反序列化、乐器匹配逻辑,维护成本高
修复方案
- 抽离公共私有方法,统一处理乐器数据读取逻辑,消除重复代码
private MusicInstrument GetTargetInstrument(string instrumentName) { string jsonContent = File.ReadAllText(filePath); var instrumentList = JsonConvert.DeserializeObject<MusicInstrumentsList>(jsonContent); return instrumentList.MusicInstruments_List.Find(i => i.InstrumentsName == instrumentName); }
- 移除所有全局
priv变量定义,单次请求的计算数据随方法返回传递,不做跨方法/跨请求的全局存储 - 给所有除法运算增加分母合法性校验,从根源避免除以零的INF错误
修复后完整代码
[WebMethod] public double[] CalInstrumentCost(String instrumentName, double instrumentQuantity) { double[] priceRange = new double[2]; try { var targetInstrument = GetTargetInstrument(instrumentName); if (targetInstrument == null) { throw new InvalidOperationException("指定乐器不存在"); } // 前置校验价格配置合法性 if (targetInstrument.MinInstrumentPrice <= 0 || targetInstrument.MaxInstrumentPrice < targetInstrument.MinInstrumentPrice) { throw new InvalidOperationException("乐器价格配置异常"); } priceRange[0] = targetInstrument.MinInstrumentPrice * instrumentQuantity; priceRange[1] = targetInstrument.MaxInstrumentPrice * instrumentQuantity; return priceRange; } catch { throw new InvalidOperationException("价格区间计算失败"); } } [WebMethod] public double HowMuchInstrument(String instrumentName, double totalBudget) { double canBuyCount = 0; try { var targetInstrument = GetTargetInstrument(instrumentName); if (targetInstrument == null || totalBudget < 0) { return canBuyCount; } double minUnitPrice = targetInstrument.MinInstrumentPrice; // 分母零值校验,彻底规避INF错误 if (minUnitPrice <= 0) { return 0; } canBuyCount = Math.Floor(totalBudget / minUnitPrice); return canBuyCount; } catch { return canBuyCount; } }
关键注意事项
- Web服务接口禁止使用全局变量存储单次请求的业务数据,并发场景下必然出现数据串扰、值未初始化等不可预期问题
- 所有涉及除法的计算逻辑,必须提前校验分母的合法性,排除0、负数等异常值
- 重复的IO、数据查询逻辑抽离为内部公共方法,减少冗余代码的同时降低后续维护成本
内容的提问来源于stack exchange,提问作者Bartu Bozkurt
相关产品推荐
相关产品推荐

