C#如何使用对象列表:按发票编号查找指定对象并调用对应方法
按发票号定位列表对象并调用支付方法的实现方案
核心实现逻辑为:从发票列表中匹配出InvoiceNumber与目标编号一致的Invoice实例,判空后直接调用对应实例的MakePayment方法即可,同时建议做好异常边界处理避免运行时报错。
实现代码示例
前提准备
如果使用LINQ语法简化查询,需要先引入对应命名空间:
using System.Linq;
1. LINQ查询实现(推荐)
// 替换为实际要查询的发票号和支付金额 string targetInvoiceNumber = "INV2024001"; double paymentAmount = 256.75; // 匹配目标发票对象 Invoice targetInvoice = LstInvoice.FirstOrDefault(inv => inv.InvoiceNumber == targetInvoiceNumber); // 非空校验后调用方法 if (targetInvoice != null) { targetInvoice.MakePayment(targetInvoiceNumber, paymentAmount); } else { // 自定义找不到发票时的处理逻辑,例如弹窗提示、写日志等 Console.WriteLine($"编号为{targetInvoiceNumber}的发票不存在"); }
2. 循环遍历实现(无需引用LINQ)
如果你不想引入LINQ命名空间,也可以用基础循环实现匹配:
string targetInvoiceNumber = "INV2024001"; double paymentAmount = 256.75; foreach (Invoice inv in LstInvoice) { if (inv.InvoiceNumber == targetInvoiceNumber) { inv.MakePayment(targetInvoiceNumber, paymentAmount); // 发票号为唯一标识,找到后直接退出循环 break; } }
现有方法优化建议
你当前的MakePayment是实例方法,调用时已经确定了对应发票对象,参数invoicenumberIn没有实际使用,可以删除冗余参数,同时增加参数校验避免业务逻辑错误:
public void MakePayment(double amount) { if (amount <= 0) { throw new ArgumentException("支付金额必须大于0"); } if (amount > CurrentInvoiceTotal) { throw new InvalidOperationException("支付金额不能超过发票剩余待支付金额"); } CurrentInvoiceTotal = InvoiceTotal - amount; }
优化后调用方法时不需要再传发票号,直接写targetInvoice.MakePayment(paymentAmount)即可。
内容的提问来源于stack exchange,提问作者Talha Haroon
相关产品推荐
相关产品推荐

