C# 如何在Customer类中实现根据客户ID删除客户的功能
该需求完全可以实现,实现方案如下:
第一步:修改Customer.cs,封装按ID删除的逻辑
由于单个Customer实例仅代表单个客户对象,操作客户集合的删除逻辑我们封装为静态方法,无需实例化即可调用,修改后的完整代码如下:
using System.Collections.Generic; using System.Linq; public class Customer { public int customerId; public string firstName; public string lastName; public string phoneNumber; public string address; public string FirstName { get { return firstName; } set { firstName = value; } } public string LastName { get { return lastName; } set { lastName = value; } } public string PhoneNumber { get { return phoneNumber; } set { phoneNumber = value; } } public string Address { get { return address; } set { address = value; } } // 封装按ID删除客户的逻辑 public static bool DeleteCustomerById(List<Customer> customerList, int targetId) { var target = customerList.FirstOrDefault(c => c.customerId == targetId); if (target == null) return false; customerList.Remove(target); return true; } }
第二步:优化Form.cs的绑定与删除逻辑
原有代码仅向列表框添加firstName会导致重名客户无法准确识别,我们改为直接绑定Customer对象,设置显示字段为FirstName,既不改变前端仅展示名字的效果,又能拿到完整的客户信息,修改后的完整代码如下:
using System.Collections.Generic; using System.Windows.Forms; public partial class AddCustomer : Form { List<Customer> list = new List<Customer>(); Random rand = new Random(); public AddCustomer() { InitializeComponent(); // 设置列表框显示客户的FirstName,用户看不到其他字段 listBoxCustomers.DisplayMember = "FirstName"; } // 添加客户 private void buttonAddCustomer_Click(object sender, EventArgs e) { Customer customer = new Customer(); customer.customerId = rand.Next(); customer.firstName = textBoxfn.Text; list.Add(customer); // 直接添加Customer对象,不要只加firstName listBoxCustomers.Items.Add(customer); } // 删除客户 private void buttonDeleteCustomer_Click(object sender, EventArgs e) { if (listBoxCustomers.SelectedItem is Customer selectedCus) { // 调用Customer类封装的删除逻辑 Customer.DeleteCustomerById(list, selectedCus.customerId); // 移除列表框中的对应项 listBoxCustomers.Items.Remove(selectedCus); } } }
逻辑说明
- 前端展示效果和需求完全一致,用户仅能看到客户的firstName,无其他额外信息
- 所有按ID匹配删除的逻辑都封装在Customer类内部,后续如果删除规则调整,只需要修改Customer类的
DeleteCustomerById方法即可,不需要改动Form层代码 - 同时修复了原有代码的隐藏问题:原有删除仅移除了列表框的项,底层
List<Customer>集合中的数据并没有被删除,修改后两端数据完全一致
内容的提问来源于stack exchange,提问作者HarryB
相关产品推荐
相关产品推荐

